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.
太棒了;这是at best an 未记录的功能功能上等效的记录在案功能存在。因此,应该not使用。
你关于“减少打字”的论点是非常可疑的;比较:
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}"
功能、错误还是 NaN?
这些都不是;这是未定义的行为。你是assuming that _i
将是编译后的 JavaScript 中用于迭代的变量。
你绝对不应该使用_i
,或假设_i
将被定义。这是一个实施细节,他们可以随时更改它。也是不会的be _i
如果您的循环嵌套在另一个循环中;这将是_j
or _k
etc.
最重要的是,你可以做这件事without依赖于底层实现的 JavaSript 变量。如果你想用索引循环,只需使用for value,key in array
:
array = ['a', 'b', 'c']
console.log(index) for item, index in array # 0, 1, 2
具体来说,在您的示例中:
feast = (cats) -> eat cat for cat, index in cats when index % 2 == 0