为什么这个咖啡脚本没有打印出来?

时间:2012-10-14 13:37:58

标签: coffeescript

所以当索引为0时,我想打印出来:

a = [ 1, 2, 3 ] 

for i of a
    if i == 0
        console.log a[i]

但没有输出。

i == 0永远不会......

3 个答案:

答案 0 :(得分:12)

我将索引作为字符串返回,如果将它们解析为整数,它将起作用

a = [ 1, 2, 3 ] 

for i of a
    if parseInt(i) == 0
        console.log a[i]

答案 1 :(得分:2)

这是因为i只会是1,2或3,因为你循环遍历a中的项目,而不是索引号。

这可以按照上面描述的方式工作:

a = [ 1, 2, 3 ] 

for i in [0..a.length]
    if i == 0
        console.log a[i]

答案 2 :(得分:1)

您不应该使用of循环数组,您应该使用in。来自fine manual

  

理解也可用于迭代对象中的键和值。使用of来表示对对象属性的理解,而不是数组中的值。

yearsOld = max: 10, ida: 9, tim: 11

ages = for child, age of yearsOld
  "#{child} is #{age}"

所以你试图迭代数组对象的属性,而不是它的索引。

你应该在循环中使用其中一个:

for e, i in a
    if(i == 0)
        console.log(a[i])

for e, i in a 
    console.log(e) if(i == 0)

console.log(e) for e, i in a when i == 0

#...

或者,既然你有一个数组和一个数字索引,为什么不跳过循环并直接指向:

console.log(a[0])
相关问题