JavaScript From Scratch: Playing With Data
-
Upload
michael-girouard -
Category
Technology
-
view
1.224 -
download
1
description
Transcript of JavaScript From Scratch: Playing With Data
JavaScript From Scratch“Playing With Data”
Agenda
• Strings
• Numbers
• Booleans
• Arrays
• Objects
Strings
• Any data surrounded by quotes
• ‘Single quotes’
• “Double quotes”
• Usually things with non-numeric characters
Strings
• Can be concatenated via the + operator
var name = ‘Mike ’ + ‘Girouard’;var sentence = name + ‘ is awesome!’;
var element = ‘p’;var content = ‘Hello, world!’;var tag = ‘<’ + element + ‘>’;
tag = tag + content;tag = tag + ‘</’ + element + ‘>’;
var element = ‘p’;var content = ‘Hello, world!’;var tag = ‘<’ + element + ‘>’;
tag += content;tag += ‘</’ + element + ‘>’;
Numbers
• Any kind of number
• 1, 2, 4, 100, 79812 (Integers)
• 1.2, 7.9, 1.2489, 1.0 (Floats)
var product = ‘Widget’;var price = 1.99;var quantity = 4;var taxRate = .08375;
var subTotal = price * quantity;var taxAmt = subTotal * taxRate;var total = subTotal + taxAmt;
Booleans
• True/False values
var canDrink = true;var canParkInBrooklyn = false;
var isOver21 = (2008 - 1983) > 21;var isEmpty = (input.value == ‘’);var isIEorOpera = (‘all’ in document);
if (isOver21) { alert(‘99 beers on the wall...’);}
if (isEmpty) { alert(‘You missed something...’); input.focus();}
if (isIEorOpera) { var url = ‘http://getfirefox.com/’; window.location = url;}
var validLogin = (user == ‘foo’ && pass == ‘bar’);
if (!validLogin) { window.location = ‘bad-login.php’;}
Arrays
• One variable, multiple values
• Use numbers to identify values
• Think about an <ol> in XHTML
• ... that starts with 0
var colors = [‘red’, ‘green’, ‘blue’];
alert(colors[0]);alert(colors[1]);alert(colors[2]);
var sentence = ‘There are ’ + colors.length + ‘ colors total’;
colors.push(‘chartreuse’);
sentence = ‘Now there are ’ + colors.length;
Objects
• Like arrays: one variable, multiple values
• Instead of numbers, objects use strings
var birthdays = { ‘Mike’ : ‘01-14-83’, ‘John’ : ‘06-23-74’, ‘Amy’ : null};
alert(birthdays.Mike);alert(birthdays.John);alert(birthdays.Amy);
Review
• Strings:
• Begin and end with quotes
• Quotes can be ‘single’ or “double”
• Concatenated with a + operator
• Appended with a += operator
Review
• Numbers:
• Any kind of numeric data
• Quotes are not necessary
Review
• Booleans:
• true or false values
• Form the basis of all logic in programming
• Can be negated with a ! operator
Review
• Arrays:
• One variable, multiple values
• Indexed by numbers
• ... beginning with 0
• New items can be added with push()
Review
• Objects:
• One variable, multiple values
• Indexed by strings
Homework
• Build a micro-library for HTML generation
• Functions should accept arguments for each attribute
• Functions should return strings as a result
Homework
• Required Functions:
• a (href, title, content)
• img (src, alt)
• p, h1 ... h6 (content)
Homework
• Required Functions:
• ol, ul (listItems)
• dl (dictionary)