问题描述
看看这个简单的代码:
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"]
$ coffee a.coffee
nom tabby cat
nom norwegian forest cat
nom american bobtail
看来 _i
变量是当前索引。这是一个功能,bug,还是NaN?我没有听说有人在说这个,所以我不知道是否有一些原因我不应该在我的代码中使用它。
It seems the _i
variable is the current index. Is this a feature, bug, or NaN? I haven't heard anyone else talking about this, so I wonder if there's some reason I shouldn't use it in my code?
推荐答案
tldr-again; CoffeeScript的作者只是告诉我:不要使用 _i
。
tldr-again; The author of CoffeeScript just told me I'm right: Don't use _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.
tldr;这是最多 ,其功能等同于记录功能存在。
tldr; This is at best an undocumented feature for which a functionally equivalent documented feature exists. As such, it should not be used.
您对less typing的论点很可疑,因此不应该使用 比较:
Your argument of "less typing" is highly dubious; compare:
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}"
这些都没有;它是未定义的行为。您假设 _i
将是用于编译JavaScript中的迭代的变量。
None of these things; it's undefined behaviour. You are assuming that _i
will be the variable used for iteration in the compiled JavaScript.
你绝对不应该使用 _i
,或者假设 _i
被定义。这是一个实现细节,他们可以随时更改它。如果你的循环嵌套在另一个循环中,它也不会 _i
它将 _j
或 _k
等。
You definitely shouldn't use _i
, or assume _i
will be defined. That's an implementation detail, and they're free to change it at any time. It's also won't be _i
if your loop is nested in another loop; it will be _j
or _k
etc.
重要的是,您可以在不需要依赖底层实现的JavaSript变量的情况下做这件事情。如果你想循环一个索引,只需使用的值,键入数组
:
Most importantly, you can do this exact thing without relying on the underlying implementation's JavaSript variables. If you want to loop with an index, just use for value,key in array
:
array = ['a', 'b', 'c']
console.log(index) for item, index in array # 0, 1, 2
具体来说,在您的示例中:
Specifically, in your example:
feast = (cats) -> eat cat for cat, index in cats when index % 2 == 0
这篇关于for循环中的索引变量(_i)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!