How would I loop over a group of JS objects and print a statement for each?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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); |
我想遍历每个语句并为每个语句打印上面的语句。我该怎么做?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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/>"); } |
P></
下面将为你的工作也让我的心灵(在箭头的browsers函数将不工作。我知道should probably be used the previous example)。P></
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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/>"); }); |
P></
你可以使用arrays to the method of
1 2 3 | teams.forEach(function(team){ document.write("The" + team.city +"" + team.nickname +" play in the" + team.league); }); |
你也可以使用更传统的for循环:P></
1 2 3 | for(var i=0; i<teams.length; ++i){ document.write("The" + teams[i].city +"" + teams[i].nickname +" play in the" + teams[i].league) } |
使用
1 2 3 | teams.forEach(i => { document.write("The" + i.city +"" + i.nickname +" play in the" + i.league); }); |
如果你必须使用你的作业
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | var teams = [ { city: 'Vancouver', nickname: 'Canucks', league: 'NHL' }, { city: 'San Jose', nickname: 'Earthquakes', league: 'MLS' }, { city: 'Sacramento', nickname: 'Kings', league: 'NBA' } ]; var printTeam = function(team){ this.city = team.city; this.nickname = team.nickname; this.leage = team.leage; document.write("The" + this.city +"" + this.nickname +" play in the" + this.league); } teams.forEach(i => { printTeam(i); }, this); |
P></