for循环不迭代每个语句

时间:2015-05-19 01:04:41

标签: javascript object for-loop

我是初学者,也曾在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
*/

4 个答案:

答案 0 :(得分:3)

使用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);
}

答案 1 :(得分:2)

你的for循环周围没有大括号,所以你已经有效地写了

for(var i = 0; i < atheletes.length; i++) {
    atheletes[i].win = (atheletes[i].name + " won " + atheletes[i].sport);
}
console.log(atheletes[i].win);

使用大括号并将两个语句放在里面。

答案 2 :(得分:1)

应该是

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);
}
}

你错过了{} for loop。

答案 3 :(得分:1)

  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 key in tim){
        // var atheletes= (atheletes[i].name + " won " + atheletes[i].sport);
        if (tim.hasOwnProperty(key)) {
            alert(key + " -> " + tim[key]);
          }
          console.log(atheletes);
  }
}
  fridays_contestants=[tim,anne]
  addWinners(fridays_contestants)