2016-08-16 148 views
3
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); 

我想遍历每个打印每个上述语句。我最好怎么做?我将如何遍历一组JS对象并为每个对象打印语句?

回答

3

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/>"); 
 
}

下也会为你工作(记住,箭头功能将不会在所有的浏览器,所以在前面的例子或许应该被使用)..

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/>"); 
 
});

1

无需使用this ..

teams.forEach(i => { 
    document.write("The " + i.city + " " + i.nickname + " play in the " + i.league); 
}); 

如果必须使用您的家庭作业的this参数,那么你就需要将PARAMS设置为当前scope。最简单的方法是创建一个新的作用域并将值分配给local function scope。就像是。

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){ 
 
\t this.city = team.city; 
 
    this.nickname = team.nickname; 
 
    this.leage = team.leage; 
 
    \t document.write("The " + this.city + " " + this.nickname + " play in the " + this.league); 
 
} 
 
         
 
teams.forEach(i => { 
 
    printTeam(i); 
 
}, this);

1

可以使用阵列的方法forEach循环阵列之上:

teams.forEach(function(team){ 
    document.write("The " + team.city + " " + team.nickname + " play in the " + team.league); 
}); 

也可以使用更传统的for循环:

for(var i=0; i<teams.length; ++i){ 
    document.write("The " + teams[i].city + " " + teams[i].nickname + " play in the " + teams[i].league) 
}