如何将 JavaScript forEach 循环/函数转换为 CoffeeScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11036721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a JavaScript forEach loop/function to CoffeeScript
提问by Edward J. Stembler
Background: I'm trying to convert some JavaScript code which uses the the Crossfilterlibrary with D3.jsdata visualization library into CoffeeScript.
背景:我正在尝试将一些使用Crossfilter库和D3.js数据可视化库的JavaScript 代码转换为CoffeeScript。
What is the best way to convert a JavaScript forEach loop/function into CoffeeScript?
将 JavaScript forEach 循环/函数转换为 CoffeeScript 的最佳方法是什么?
Here's the JavaScript code:
这是 JavaScript 代码:
// A little coercion, since the CSV is untyped.
flights.forEach(function(d, i) {
d.index = i;
d.date = parseDate(d.date);
d.delay = +d.delay;
d.distance = +d.distance;
});
Can CoffeeScript do an in-line function inside a loop? Right now I'm guess I need it broken out into a function and loop:
CoffeeScript 可以在循环内执行内联函数吗?现在我想我需要把它分解成一个函数和循环:
coerce = (d) ->
d.index = 1
d.date = parseDate(d.date)
d.delay = +d.delay
d.distance = +d.distance
coerce(flights) for d in flights
回答by hvgotcodes
use a comprehension
使用理解
for d, i in flights
console.log d, i
The code above translates to
上面的代码转换为
var d, i, _i, _len;
for (i = _i = 0, _len = flights.length; _i < _len; i = ++_i) {
d = flights[i];
console.log(d, i);
}
so you can see d
and i
are what you want them to be.
所以你可以看到d
并且i
是你想要的。
Go hereand search for "forEach" for some examples.
转到此处并搜索“forEach”以获取一些示例。
Finally, look at the first comment for some more useful info.
最后,查看第一条评论以获取更多有用的信息。
回答by Scott Weinstein
The direct translation is:
直接翻译是:
flights.forEach (d, i) ->
d.index = i
d.date = parseDate(d.date)
d.delay = +d.delay
d.distance = +d.distance
or you can use an idiomatic version:
或者您可以使用惯用版本:
for d,i in flights
d.index = i
d.date = parseDate(d.date)
d.delay = +d.delay
d.distance = +d.distance
回答by user3773172
forEach has the advantage of wrapping each iteration in a closure. so asynchronous calls can preserve the correct values. the coffeescript way of doing this (without actually using forEach) is
forEach 的优点是将每次迭代都包装在一个闭包中。所以异步调用可以保留正确的值。这样做的咖啡脚本方式(实际上不使用 forEach)是
for d,i in flights
do (d, i)->
d.index = i
d.date = parseDate(d.date)
d.delay = +d.delay
d.distance = +d.distance
this compiles to something very similar to the OP's sample:
这编译为与 OP 示例非常相似的内容:
_fn = function(d, i) {
d.index = i;
d.date = parseDate(d.date);
d.delay = +d.delay;
return d.distance = +d.distance;
};
for (i = _i = 0, _len = flights.length; _i < _len; i = ++_i) {
d = flights[i];
_fn(d, i);
}
Use this if you need < ie9 support (forEach supported in IE starting version 9)
如果您需要 < ie9 支持,请使用它(在 IE 开始版本 9 中支持 forEach)