为什么迭代循环次数太多?

时间:2016-04-07 01:05:01

标签: javascript node.js

我试图通过matchId的值匹配对象匹配但是当我在match.length = 2时使用循环然后console.log(i)返回8次?

这是我的代码:

lolapi.MatchList.getBySummonerId(obj['savisaar2'].id, options, function(err, matches) {
    for (var matchId in matches) {
      var game = matches.matches;

      for(var i = 0; i < game.length; i++) {
        console.log(i);
      }
    }
  });

对象的返回如下:

{ 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 }

谢谢你们

2 个答案:

答案 0 :(得分:0)

for中的嵌套foreach循环似乎会触发此问题,因为您将迭代matches.length * match.games.length

// This will iterate for each match
for (var matchId in matches) {
    // Is this intentional (should this be matchId.matches?)
    var game = matches.matches;
    // This will iterate for each game (in each match)
    for(var i = 0; i < game.length; i++) {
       console.log(i);
    }
}

因此,如果您有两个匹配并且循环迭代八次,则意味着您的两个match对象之间有八个游戏。

答案 1 :(得分:0)

您的for (var matchId in matches)循环(for...in loop)正在循环返回对象的属性 keys ,这意味着以下密钥正在循环['matches', 'startIndex', 'endIndex', 'totalGames'],即4次。

然后内循环重复你的返回对象matches数组(2个成员),因此4*2 = 8

如果你想记录matchIds,你想要做的就是这样:

lolapi.MatchList.getBySummonerId(obj['savisaar2'].id, options, function(err, matches) {
  var gameMatches = matches.matches;

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

或者在功能上做得更多(在Internet Explorer 8中不起作用):

lolapi.MatchList.getBySummonerId(obj['savisaar2'].id, options, function(err, matches) {
  matches.matches.forEach(function(gameMatch){
      console.log(gameMatch.matchId);
  });
  // Outputs:
  // 122934310
  // 122510663
});