如何在列表推导中使用变量?

时间:2013-03-05 10:05:34

标签: coffeescript

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

试一试online

2 个答案:

答案 0 :(得分:1)

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

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

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

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

更新

如果您不需要变量numberprocess

,请使用此变量
result = ([function1(process = /* costly calculation */), function2(process), function3(process)] for number in [1, 2, 3])

答案 1 :(得分: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)]