Objects are frequently stored in arrays. Let's create a few objects.
var tom = {
name: "tom",
job: "plumber"
}
var phil = {
name: "phil",
job: "teacher"
}
var susan = {
name: "susan",
job: "doctor"
}
Now we can store tom, phil, and susan in an array of people.
var people = [tom, phil, susan];
It is easy to iterate over an array of objects and print information to the console. Take note that this code is relatively easy to read.
for (var i = 0; i < people.length; i++) {
var person = people[i];
console.log(person.name + " is a " + person.job)
}
This for loop will print the following output to the console.
tom is a plumber phil is a teacher susan is a doctor
When the same data is stored in a nested array, the for loop is harder to read.
var peopleData = [
["tom", "plumber"],
["phil", "teacher"],
["susan", "doctor"]
]
for (var i = 0; i < peopleData.length; i++) {
console.log(peopleData[i][0] + " is a " + peopleData[i][1]);
}
Arrays of objects are very common in JavaScript.
Question | Click to View Answer |
What does the following code print to the console? var cat = {
name: "garfield",
mood: "blah"
}
var crazy = {
name: "rambo",
mood: "angry"
}
var random = [cat, crazy];
for (var i = 0; i < random.length; i++) {
var thing = random[i];
console.log(thing.name + " is " + thing.mood);
}
|
garfield is blah rambo is angry The for loop iterates through every element in the random array and prints a message to the console. |
What does the following code print to the console? var testOne = {
score: 63,
date: "2015-01-04"
}
var testTwo = {
score: 85,
date: "2015-02-07"
}
var testThree = {
score: 74,
date: "2015-05-10"
}
var tests = [testOne, testTwo, testThree];
var countPassingTests = 0;
for (var i = 0; i < tests.length; i++) {
var test = tests[i];
if (test.score > 65) {
countPassingTests++;
}
}
console.log(countPassingTests);
|
2 The for loop iterates over all the tests and increments the countPassingTests variable whenever the score is greater than 65. The countPassingTests variable is then printed to the console. |