2

我有以下 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 中做到这一点?

在线尝试!

4

2 回答 2

1

在 CoffeeScript 块中也是表达式,所以你可以这样做:

result = (process = costlyCalculation(); [number, function1(process), function2(process), function3(process)] for number in [1, 2, 3])

或者,我建议不要使用分号来分隔语句,而是使用换行符:

result = for number in [1, 2, 3]
  process = costlyCalculation()
  [number, function1(process), function2(process), function3(process)]
于 2013-03-05T13:45:16.087 回答
1

执行此操作,这应该可以解决您的问题:

result = ([number = (process = /* costly calculation */) - process + number, function1(process), function2(process), function3(process)] for number in [1, 2, 3])

在这里,将为数组中的每个数字执行两个额外的操作(加法和减法)。但是,它不应该增加太多的计算成本。

可以进一步优化以降低计算成本。

更新:

当你不需要变量时使用number这个process

result = ([function1(process = /* costly calculation */), function2(process), function3(process)] for number in [1, 2, 3])
于 2013-03-05T10:19:22.683 回答