如何在Javascript中循环遍历以下对象?

时间:2016-04-06 02:55:37

标签: javascript

我一直在设法绕过这个返回此对象的方法:

{ 
  matches: [ 
    { 
      region: 'OCE',
      platformId: 'OC1',
      matchId: 122934310,
      champion: 36,
      queue: 'TEAM_BUILDER_DRAFT_RANKED_5x5',
      season: 'SEASON2016',
      timestamp: 1456100362493,
      lane: 'BOTTOM',
      role: 'DUO_SUPPORT' 
    },
    { 
      region: 'OCE',
      platformId: 'OC1',
      matchId: 122510663,
      champion: 44,
      queue: 'TEAM_BUILDER_DRAFT_RANKED_5x5',
      season: 'SEASON2016',
      timestamp: 1455751169038,
      lane: 'BOTTOM',
      role: 'DUO_SUPPORT' 
    } 
  ],
  startIndex: 0,
  endIndex: 2,
  totalGames: 135 
}

我是一名php开发人员,所以我会在这种情况下使用foreach但是我似乎无法弄清楚javascript。感谢

我需要遍历每个matchId

当前代码:

app.get('/summoner/:summonerName', function(req, res) {
lolapi.Summoner.getByName(req.params.summonerName, function(err, obj) {
  var options = {
    beginIndex: 0,
    endIndex: 2
  };
  lolapi.MatchList.getBySummonerId(obj['savisaar2'].id, options,   function(err, matches) {
    for(var i = 0; i < obj.matches.length; i++) { console.log(obj.matches[i].matchId); }
  });
});
});

3 个答案:

答案 0 :(得分:0)

根据以下评论更新此内容。

您的外部对象称为matches。您要做的是迭代该对象中的数组(也称为matches),并为数组中的每个对象打印matchId。你可以用:

来做到这一点
var matches = matches.matches;
// If you get an error here, it means the `matches` object either doesn't exist, or, it doesn't contain an array called `matches`

for(var i = 0; i < matches.length; i++) {
  console.log(matches[i].matchId);
}

答案 1 :(得分:-1)

LoopCount = 0;
while (1==1){
LoopCount = LoopCount + 1;
if (LoopCount == //numberOfTimesToLoop){
break};
//YourCode
};

答案 2 :(得分:-1)

如果您的浏览器支持ES6(大部分都是),您可以使用以下脚本:

for (var m of obj.matches){
    console.log(m.matchId);
}