我是一个初学者,并且也对 Ruby 有过一段时间的了解,所以我可能在这里遗漏了一些小东西。
但我很好奇为什么每次迭代 [i] 时都会跳过console.log(atheletes[i].win);?我发现当计数器到达该点时,它已经是 2,因此它返回 undefined,因为它已经超出了数组的末尾。
奇怪的是,如果我将分号从前面的语句更改为逗号,它就可以工作。因此,由于某种原因,迭代器仅适用于第一个语句。
var tim = {
name : "Tim",
height : 71,
sport : "soccer",
quote : "Timmy the Tiger!"
}
var anne = {
name : "Anne",
height : 66,
sport : "zumba",
quote : "Anne Gonna Dance All Over Ya!"
}
//function to add a "win" property and default value to each athlete object
function addWinners(atheletes){
for(var i = 0; i < atheletes.length; i++)
atheletes[i].win = (atheletes[i].name + " won " +
atheletes[i].sport);
console.log(atheletes[i].win);
}
fridays_contestants=[tim,anne]
addWinners(fridays_contestants)
/*
Current output:
=>"Cannot read property 'win' of undefined"
Desired output:
=>Tim won soccer
=>Anne won zumba
*/
最佳答案
您没有使用 { ... }
在 for
循环之后启动代码块。这样,只有紧接在循环之后的语句才会在循环内执行。之后的所有内容都将在循环完成且 i
等于 2 后执行。编辑:i
在您调用 时实际上应该不再存在console.log()
,因为它超出了范围 - 它已在 for
语句内声明。
尝试像这样:
for(var i = 0; i < atheletes.length; i++) {
atheletes[i].win = (atheletes[i].name + " won " +
atheletes[i].sport);
console.log(atheletes[i].win);
}
关于javascript - For 循环不迭代每个语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315161/