在 Coffeescript 中迭代 ES6 Set/Map(使用 `of` 运算符)

2022-01-24 00:00:00 javascript ecmascript-6 coffeescript

如何迭代 ES6 Map 或 在Coffeescript中设置?

在 Javascript 中可以使用例如

s = new Set()s.add({a: 1})对于 (x of s) {控制台.log(x);}

但是 Coffeescript 有自己的 of 运算符,可以转换为 in,即:

console.log(x) for x of s

变成 ... for (x in s) { ... }.

如何在 Coffeescript 中访问 Javascript 的 of 运算符?

可以通过循环s.values().next() 来编写自己的自定义迭代器,但那将是可憎的.:)

解决方案

Coffeescript 2.0 —for …from

<块引用>

JavaScript 的 for...of 现在可以作为 CoffeeScript 的 for ...from 使用(我们已经有一个 for ...of): for n from generatorFunction()

Coffeescript 1.0 - 反引号

一种选择是使用反引号嵌入原始 Javascript,即 http://coffeescript.org/#embedded.

`for (x of y) { }`

How can one iterate over an ES6 Map or Set in Coffeescript?

In Javascript one would use e.g.

s = new Set()
s.add({a: 1})
for (x of s) {
  console.log(x);
}

However Coffeescript has its own of operator that gets converted to in, i.e.:

console.log(x) for x of s

becomes ... for (x in s) { ... }.

How can one access Javascript's of operator in Coffeescript?

One could write their own custom iterator by cycling over s.values().next(), but that'd be an abomination. :)

解决方案

Coffeescript 2.0 — for …from

JavaScript’s for…of is now available as CoffeeScript’s for …from (we already had a for …of): for n from generatorFunction()

Coffeescript 1.0 — Backticks

One option is to use the backtick to embed raw Javascript i.e. http://coffeescript.org/#embedded.

`for (x of y) { }`

相关文章