【发布时间】:2015-05-19 01:04:40
【问题描述】:
我是一个初学者,并且对 Ruby 也有一定的了解,所以我可能在这里遗漏了一些小东西。
但我很好奇为什么 console.log(atheletes[i].win); 会在 [i] 的每次迭代中被跳过?我发现当计数器到达那个点时,它已经是 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
*/
【问题讨论】:
标签: javascript object for-loop