Arrays filled with objects will work just like arrays filled with numbers and strings.
In the same way we may loop through an array of numbers to print them out or calculate a sum, we can loop through an array of objects and access properties or methods.
Instructions
- Write a person constructor called
Person
that has two properties (name
andage
). - Create an empty array called
family
. - There will be four objects in the array. Using your
Person
constructor, create the four objects and put them in the array. The order of the objects are:"alice"
who is40
"bob"
who is42
"michelle"
who is8
"timmy"
who is6
- Create a
for
-loop that loops through thefamily
array and prints out thename
property for each family member in order of creation.
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("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);
// add the last family member, "timmy", who is 6 years old
// Our Person constructor
for(i=0;i<4;i++){console.log(family[i])};
// loop through our new array
No comments:
Post a Comment