且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-19 22:01:36

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}"








功能,bug或NaN?

feature, bug, or NaN?

这些都没有;它是未定义的行为。您假设 _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