var teams = [
{
city: 'Vancouver',
nickname: 'Canucks',
league: 'NHL'
},
{
city: 'San Jose',
nickname: 'Earthquakes',
league: 'MLS'
},
{
city: 'Sacramento',
nickname: 'Kings',
league: 'NBA'
}
]
document.write("The " + this.city + " " + this.nickname + " play in the " + this.league);
I want to loop through each and print the above statement for each. How would I best do this?
var teams = [{
city: 'Vancouver',
nickname: 'Canucks',
league: 'NHL'
},
{
city: 'San Jose',
nickname: 'Earthquakes',
league: 'MLS'
},
{
city: 'Sacramento',
nickname: 'Kings',
league: 'NBA'
}];
for (var i = 0; i < teams.length; i++) {
var team = teams[i];
document.write("The " + team.city + " " + team.nickname + " play in the " + team.league + "<br/>");
}
The following will also work for you (keep in mind that arrow functions will not work in all browsers. So the previous example should probably be used)..
var teams = [{
city: 'Vancouver',
nickname: 'Canucks',
league: 'NHL'
},
{
city: 'San Jose',
nickname: 'Earthquakes',
league: 'MLS'
},
{
city: 'Sacramento',
nickname: 'Kings',
league: 'NBA'
}];
teams.forEach(team => {
document.write("The " + team.city + " " + team.nickname + " play in the " + team.league + "<br/>");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With