for循环中的索引变量(_i)?

Dog*_*Dog 4 undefined-behavior coffeescript

看看这个简单的代码:

eat = (x) -> console.log "nom", x

# dog only eats every second cat
feast = (cats) -> eat cat for cat in cats when _i % 2 == 0

feast ["tabby cat"
       "siamese cat"
       "norwegian forest cat"
       "feral cat"
       "american bobtail"
       "manx"]
Run Code Online (Sandbox Code Playgroud)
$ coffee a.coffee 
nom tabby cat
nom norwegian forest cat
nom american bobtail
Run Code Online (Sandbox Code Playgroud)

似乎_i变量是当前的指数.这是功能,错误还是NaN?我没有听到其他人在谈论这个,所以我想知道是否有一些原因我不应该在我的代码中使用它?

mea*_*gar 14

tldr,再次; CoffeeScript的作者告诉我我是对的:不要使用_i.

14:29 <jashkenas> You shouldn't use internal variables. 
...
14:42 <meagar> I was hoping something more deeply involved in the language would be able to put some authority behind that opinion 
14:43 <meagar> ... I was basically hoping for an authoritative "don't do that" 
14:44 <jashkenas> you just got it ;) 
14:44 <jashkenas> for item, index in list -- there's your reference to the index. 
Run Code Online (Sandbox Code Playgroud)

tldr; 这充其量是一个未记录的功能,其中存在功能相同的文档功能.因此,应该使用它.

你的"少打字"的论点非常可疑; 相比:

for x in [1, 2, 3] when _i % 2 == 0
  console.log "#{_i} -> #{x}"

for x,i in [1, 2, 3] when i % 2 == 0
  console.log "#{i} -> #{x}"
Run Code Online (Sandbox Code Playgroud)

功能,错误或NaN?

这些都不是; 这是未定义的行为.您假设_i将是用于编译JavaScript中的迭代的变量.

你肯定不应该使用_i,或假设_i将被定义.这是一个实现细节,他们可以随时更改它.它也不会 _i,如果你的循环嵌套在另一个循环; 这将是_j_k

最重要的是,您可以在依赖底层实现的JavaSript变量的情况下完成此操作.如果要循环索引,只需使用for value,key in array:

array = ['a', 'b', 'c']

console.log(index) for item, index in array # 0, 1, 2
Run Code Online (Sandbox Code Playgroud)

具体来说,在您的示例中:

feast = (cats) -> eat cat for cat, index in cats when index % 2 == 0
Run Code Online (Sandbox Code Playgroud)