Javascript 为什么迭代循环次数太多?
我试图通过matchId值的对象匹配进行循环,但是当match.length=2时使用循环,然后console.log(I)返回8次 这是我的密码:Javascript 为什么迭代循环次数太多?,javascript,node.js,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 =
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);
}
}
});
谢谢各位看来您的
foreach
中嵌套的for
循环将触发此操作,因为您将迭代匹配。长度
*匹配。游戏。长度
:
// 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);
}
}
//这将对每个匹配进行迭代
for(匹配中的var matchId){
//这是故意的(应该是matchId.matches吗?)
var game=matches.matches;
//这将在每场比赛中迭代
对于(变量i=0;i
因此,如果您有两个匹配项,并且循环迭代了八次,这意味着您的两个match
对象之间有八个游戏。您的for(var matchId in matches)
loop(a)正在循环返回对象的属性键,这意味着正在循环以下键['matches','startIndex','endIndex','totalGames']
,即4次
然后内部循环重复返回对象的匹配
数组(2个成员),从而4*2
=8
如果要记录MatchID,可能需要执行以下操作:
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);
}
});
嵌套的for循环是故意的吗?
for(匹配中的var matchId){
您的内部循环似乎根本没有使用matchId
?
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);
}
});
lolapi.MatchList.getBySummonerId(obj['savisaar2'].id, options, function(err, matches) {
matches.matches.forEach(function(gameMatch){
console.log(gameMatch.matchId);
});
// Outputs:
// 122934310
// 122510663
});