我有以下 Coffeescript 代码:
result = ([number, process = number * 2, process] for number in [1, 2, 3])
编译成:
var number, process, result;
result = (function() {
var _i, _len, _ref, _results;
_ref = [1, 2, 3];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
number = _ref[_i];
_results.push([number, process = number * 2, process]);
}
return _results;
})();
结果是一个多维数组:
[ [1, 2, 2], [2, 4, 4], [3, 6, 6] ]
让我们假设process
计算成本非常高,我想将该值用作几个不同函数的参数:
result = ([number, process = /* costly calculation */, function1(process), function2(process), function3(process)] for number in [1, 2, 3])
这实际上很好。但是,我不希望process
自身的值成为结果数组的元素。它的值现在仍然是数组的第二个元素。当我查看编译后的 Javascript 时,我可以轻松地将定义process
移出数组,如下所示:
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
number = _ref[_i];
process = number * 2;
_results.push([number, process]);
}
如何在 Coffeescript 中做到这一点?
在线尝试!