Blog of Jeff A blog about programming and random other things.

30Jun/09link

“Brief” Guide to JavaScript – Part 4

Here we’re covering Arrays & Objects. I’m also testing out the some code display plugin for Live Writer. It’s not perfect, but it's better than no color.


Arrays

Arrays are a typical programming paradigm. It allows us to store multiple values into one variable, usually the values are related in some way or another. Let's say we want to store a list of our grades for a particular class:

var grades = [80, 93, 66, 97];

If we want to access individual elements of the array, we use a number that represents where its located in the list, where zero is the first element.

alert(grades[0]); // displays 80
alert(grades[1]); // displays 93
alert(grades[2]); // displays 66
alert(grades[3]); // displays 97

Grades stores an array which contains 4 elements (not to be confused with html elements). We can verify the size of the array by accessing the length property.

var size = grades.length; // size stores 4 (assuming grades is the array from above)

This property is pretty handy if we wanted to calculate our average:

var average = 0; // set value
for(var i=0; i<grades.length; i++){ // i is from 0 to 3
    average += grades[i]; // we add the grade at i to average
}
average /= grades.length; // divide by the number of grades

Here, we utilize our handy friend, the for loop, and use i which increments by one starting at zero (where our first element would be) to the length of grades minus one (where the last element would be). This allows us to access each element in grades. We then add each element we access to our average variable before dividing by the total number of grades. Cool huh? :)

Using an array saved us all the effort of manually adding each grade if we stored each grade as an individual variable.

Arrays are more than a static list. Like any other variables, we can also assign new values to array elements:

grades[2] = 101; // the evil people we are, upping our grades :) 

We can just as easily add new grades at the end of the array:

grades.push(86); // now grades[4] has 86

An alternative is to do this:

grades[grades.length] = 86;

And remove grades from the end of the array if we wanted to:

// removes the grade we just added earlier. Stores 86 to last_grade.
var last_grade = grades.pop();

It's also worth noting that elements in an array can be any kind of data:

var mylist = ["web", 2.0]; // perfectly fine
alert(mylist[0]); // displays web
alert(mylist[1]); // displays 2.0

There are more methods and properties which you can read over at W3Schools if you have a curiosity to feed.

Objects

Nearly everything in JavaScript are represented as basic types (string, int, float, etc.), functions, or objects. The special feature of objects is that it can house more data.

Objects are broken down to two things: keys and values. If you're coming from another programming language, objects are similar to hashes or dictionaries.

Let's say we want to store a simple address book:

// john & tina are called keys, while the phone numbers are called values.
var book = {john: "123-456-7890", tina: "098-765-4321"};

Here book stores two people: john and tina and their phone numbers (as strings). We can access the phone numbers like so:

alert(book.john); // displays john's phone number
alert(book.tina); // displays tina's phone number
alert(book['john']); // also works. displays john's phone number

Any property we didn't assign are undefined (like unassigned variables):

alert(book.joe); // undefined

Like arrays, we can add new people quite easily:

book.bob = "200-300-1337";
book.cathy = "444-555-6666";

We can iterate over the each name using a modified version of a for loop, aptly named the foreach loop.

for(var name in book){
    // prints "<name>'s phone number is <phone number>"
    // for each person in our address book
    alert(name+"'s phone number is "+book[name]);
}

The foreach loop can also work in arrays. The variable we provide in the foreach loop will be the index number the element is located

var arr = [1, 2, 3, 4, 5];
for(var i in arr){
    // displays 1, 2, 3, 4, 5 in their own alert boxes
    alert(arr[i]);
}

We can use objects in conjunction with anonymous functions for something more complex than our simple address book.

var myContainer = {
    items: [],
    length: 0,
    push: function(item){
        myContainer.items.push(item); // adds to our list.
        myContainer.length = myContainer.size();
    },
    size: function(){ return myContainer.items.length; }
};
myContainer.push('hello'); // add item
for(var i=0; i<myContainer.length; i++){    // alerts out all items in array, which is only 'hello'

    alert(myContainer.items[i]);
}

This simply encapsulates an array through our object. We can access the array directly, but we can also call any associated functions. If you plan on creating classes (see Object-Oriented Programming), I don't recommend you to do this unless you intend on creating static classes.

As a sidenote, keys can be more than just alpha numerical values, you can use almost any character, but you must enclose them as strings:

var addressbook = {
     'john-fredrick': '123-456-7980'
};
// this doesn't work: 
addressbook.john-fredrick
// this does: 
addressbook['john-fredrick']

 


We’ll that’s it for this week. Next we’ll get an overview of the DOM tree. As always, utilizing what you learn is the best way to retain the knowledge. Read part 5.

  • Share/Bookmark
blog comments powered by Disqus

Recent Posts

Topics

Archives

Following

Links