迭代ES6集/ Coffeescript中的映射(使用`of`运算符) [英] Iterate over ES6 Set/Map in Coffeescript (with `of` operator)
问题描述
如何迭代ES6 地图或在Coffeescript中设置?
在Javascript中,可以使用例如
In Javascript one would use e.g.
s = new Set()
s.add({a: 1})
for (x of s) {
console.log(x);
}
但是Coffeescript有自己的 $ c>运算符转换为
在
,即:
However Coffeescript has its own of
operator that gets converted to in
, i.e.:
console.log(x) for x of s
变为 ... for
如何访问JavaScript的
How can one access Javascript's of
operator in Coffeescript?
可以通过循环遍历 s.values()。next()来创建自己的定制迭代器
,但那是可憎的。 :)
One could write their own custom iterator by cycling over s.values().next()
, but that'd be an abomination. :)
推荐答案
目前没有办法使用新的JavaScript ES6
operator from coffeescript(1.9.2版)。现在最好的选择是使用 s.forEach(x) - > ...
或 m.forEach(value,key) - >
。
There's currently no way to use the new Javascript ES6 of
operator from coffeescript (as of 1.9.2). The best option for now is to use s.forEach (x) -> ...
or m.forEach (value, key) ->
as mentioned above.
一组:
s = new Set
s.add {a: 1}
s.forEach (v) =>
console.log v
对于地图:
m = new Map
m.set {a: 1}, {b: 2}
m.forEach (v, k) =>
console.log k, v
如果你想避免创建新的函数, ,你可以直接使用coffeescript中的迭代器。但它有点讨厌。对于集合:
If you want to avoid creating new functions for whatever reason, you can use iterators directly from coffeescript. But its a little bit nasty. For sets:
i = s.values()
while(v = i.next(); !v.done)
console.log v.value
对于地图:
i = m.entries()
while(v = i.next(); !v.done)
[key, value] = v.value
console.log key, value
括号on while循环是必要的,以使while循环依赖于v.done。
The parentheses on the while loop are necessary to make the while loop dependant on v.done.
它们也可以在一行上 - 但它看起来很不好:
They can be done on one line too - but it looks pretty bad:
i = s.values(); console.log v.value while(v = i.next(); !v.done)
这篇关于迭代ES6集/ Coffeescript中的映射(使用`of`运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!