[]
.
var names = ["Jim", "Jimmy", "Jill"];
log( names[1] );
names[2] = "Jan";
log( names );
Arrays have a built-in property called length
. The length
property will always equal the number of objects in the array.
var names = ["Jim", "Jimmy", "Jill"];
log( names );
log( names.length );
The length
property is useful when you want to iterate over each item in the array.
var numOfNames = names.length;
for (var i=0; i < numOfNames; i++) {
log( names[i] );
}
keys
.Sometimes dictionaries are also called key-value stores or hash maps.
The simplist way to make a dictionary is using the object literal syntax.
var cat = {
name: 'sprinkles',
age: 2,
gender: 'female'
};
In Javascript, dictionaries are just objects.
.
var person = {
age: 24,
"first-name": "Joe",
"last-name": "Shmoe"
};
.
operator that we used for accessing object properties earlier only works if the property name (aka key) is a valid variable identifier..
var person = {};
person["age"] = 24;
person["first-name"] = "Joe";
person["last-name"] = "Shmoe";
log( person["first-name"] );
This is similar to the []
syntax we use with arrays.
Note: The .
notation is preferred when you can use it (i.e. the key is a valid identifier)
One other nifty use of [] when dealing with dictionaries:
var person = {
age: 24,
"first-name": "Joe",
"last-name": "Shmoe"
};
var nameKey = "first-name";
log( person[nameKey] );
This is particularly useful on the next slide...
for in
loopThe for in
loop looks like this:
var shape = { width: 25, height: 50 };
for (var key in shape) {
log("Key: " + key);
log("Value: " + shape[key]);
log("----------------------");
}
key
variable simply holds a string containing the property name.key
is not a special name. Call the variable whatever you want (propertyName
for example).Anything that you can put into a variable!
Anything that you can put into a variable!
Remember how we can have objects as properties of an object?
var worker = {
name: 'Johnny',
position: 'Software Engineer',
boss: {
name: 'Fred',
position: 'TPM'
}
};
var bossOfWorker = worker.boss;
log(bossOfWorker.name);
// Or write it like this:
log( worker.boss.name );
Just like we can have objects in objects, we can have arrays of arrays
var ticTacToe = [
['X', 'O', 'O'],
['O', 'O', 'X'],
['X', 'X', 'O']
];
var secondRow = ticTacToe[1];
log( secondRow[1] );
// or write it like this:
log( ticTacToe[1][1] );
We can have an array that stores objects.
var people = [
{
firstName: 'Brandon',
lastName: 'Carpenter'
},
{
firstName: 'Kaiti',
lastName: 'Carpenter'
},
{
firstName: 'Genevieve',
lastName: 'Carpenter'
}
];
var secondPerson = people[1];
log( secondPerson.firstName );
// or write it like this
log( people[1].firstName );
We can have an object that stores arrays.
var allGrades = {
introToProgramming: [97, 67, 84, 92],
webDev2: [89, 95, 98, 79],
design1: [94, 82, 59, 100]
};
var myWebDev2 = allGrades.webDev2;
log( myWebDev2[3] );
// or write it like this
log( allGrades.webDev2[3] );
var students = [
{
name: 'Julie',
grades: [ 100, 69, 92, 88 ]
},
{
name: 'Timothy',
grades: [ 77, 79, 86, 92 ]
}
];
log( students[0]['grades'][1] );
// or
log( students[0].grades[1] );
var tweet = {
"created_at": "Wed Dec 05 18:17:16 +0000 2012",
"id": 276389793724784640,
"text": "I'm pretty sure Genevieve needs this. @kaiticarp https:\/\/t.co\/tLVoSbVY via @scoutmob",
"user": {
"id": 23104052,
"name": "Brandon Carpenter",
"screen_name": "bhcarpenter",
"location": "Atlanta, GA",
"statuses_count": 549
},
"coordinates": null,
"retweet_count": 0,
"geo": {
"type": "Point",
"coordinates": [ 33.80940075, -84.43679675 ]
}
};
Creating arrays and objects using [] and {} is so easy (and easy to read) that people have started organizing data this way all over the place. They even gave it a name: JavaScript Object Notation.
Here are some places that you may run across JSON:
jQuery is a library of functions and objects that provide an *abstraction* for working with the DOM.
var el = jQuery('#testParagraph');
// el is now a jQuery object that *represents*
// the DOM element of the paragraph above.
el.css('color', '#0000ff')
jQuery objects are objects returned by the jQuery() function. They represent (i.e. they "are an abstraction for") DOM elements. This means that you can manipulate these objects and the resulting DOM objects will reflect the change.
Note: To save typing, the jQuery() function is also aliased to $() by default. Going forward, we're just going to type $() instead of jQuery().
Instead of just finding elements by their ID, jQuery actually lets you find DOM elements using CSS selectors.
var allH1Elements = $('h1');
allH1Elements.css('text-decoration', 'underline');
You can even target elements like this:
var el = $('h1.slide15');
el.css('color', '#3465A4')
jQuery provides a replacement for most DOM manipulations.
el.attr('attrName'); // Retrieve an attribute
el.attr('attrName', 'new content'); // Set an attribute to a new value.
el.css('background', '#ff0000'); // Changes a CSS property
el.css('background'); // Retrieves the current value of a CSS property.
el.append('<p>Some HTML <strong>content</strong></p>')
el.val(); // Returns the value of an input, textarea, or select
el.val("A value"); // Sets the value of an input, textarea, or select
Finally, jQuery also provides a way to register event listeners. Test Link
var el = $('#testLink4');
var handler = function(event) {
// Don't actually follow the link:
event.preventDefault();
// Instead print out what the link URL is.
var url = el.attr('href');
log(url);
}
el.on('click', handler);
You can also fake events! Check this out.
var el = $('#testLink4');
el.trigger('click');
jQuery also creates a special event on the document object called "ready". It is triggered after all of the elements of the DOM have been created.
If you put your JavaScript tags in the <head> tag, there's a good chance that the DOM events you want to work with haven't been loaded yet, because your web browser creates the DOM elements as it reads the HTML top-to-bottom. If you put all of your DOM code inside of an event listener attached to the "ready" event of the document object, all of the DOM elements are guaranteed to exist.
We haven't been worrying about this because we include all of our JavaScript at the very bottom of the page, but you'll see this a lot as you work with other people's JavaScript code. See the jQuery documentation for more information about the "ready" event.
We've only touched the surface of what jQuery can do.
There are numerous tutorials that you can follow to hone your jQuery skills. Also, the online documentation is excellent.
For any future DOM-type stuff on your homework, feel free to use jQuery instead of document.getElementById()
, addEventListener()
, etc.
Table of Contents | t |
---|---|
Exposé | ESC |
Presenter View | p |
Source Files | s |
Slide Numbers | n |
Notes | 2 |
Help | h |