Thursday, April 18, 2013

Javascript: Combining Objects with Arrays, Loops, and Functions


a slice of coconut cake @ souen

Objects are just another type--like a string or number, but a bit more complex. So just as we can make arrays of strings and numbers, we can also makes arrays of objects:

// here, we have a person constructor:
function Person (name, age) {
    this.name = name;
    this.age = age;
};

// now we can make an array of people:
var family = new Array();
family[0] = new Person("jenny", 18);
family[1] = new Person("alex", 13);
family[2] = new Person("mom", 51);
family[3] = new Person("dad", 49);

Arrays filled with objects will work just like arrays filled with numbers and strings. In the same we we can loop through an array of numbers to print them out or to calculate a sum, we can loop through an array of objects and access properties or methods:

// loop through our new array and print out the name of each family member:
for (i = 0; i < family.length; i++ )
{console.log(family[i].name)
};

We can also use objects as parameters for functions as well. That way, we can take advantage of the methods and properties that a certain object type provides. In addition to our Person constructor, we have also introduced a new function, ageDifference. This function takes two Person objects as parameters and returns the difference in age between the two people:

// create var ageDifference
var ageDifference = function(person1, person2) {
    return person1.age - person2.age;
};

// create multiple example people
var jenny = new Person("Jenny", 18);
var alex = new Person("Alex", 13);

// create new variable diff
var diff = ageDifference(jenny, alex);

1 comment:

  1. thanks - this helped me out with a project I was working on today.

    ReplyDelete