是否可以在Underscore.js中同时迭代两个列表?

mrj*_*emp 10 functional-programming underscore.js

我基本上想要使用_.each()_.map()在Underscore.js中表达以下行为.

a = [1, 2, 3]
b = [3, 2, 1]

# Result list
c = [0, 0, 0]

for i in [0 .. a.length - 1]
   c[i] = a[i] + b[i]
Run Code Online (Sandbox Code Playgroud)

这在Matlab(我的主要语言)中绝对是可能的:

c = arrayfun(@(x,y) x+y, a, b)
Run Code Online (Sandbox Code Playgroud)

直觉上,感觉Underscore中的语法应该是:

c = _.map(a, b, function(x, y){ return x + y;})
Run Code Online (Sandbox Code Playgroud)

但是,该参数列表是不可接受的; 第二个参数应该是一个可调用的函数.

在这种情况下,可选的"上下文"参数对我没有帮助.

icy*_*com 16

使用zip(也来自underscore.js).像这样的东西:

var a = [1, 2, 3];
var b = [4, 5, 6];
var zipped = _.zip(a, b);
// This gives you:
// zipped = [[1, 4], [2, 5], [3, 6]]

var c = _.map(zipped, function(pair) {
  var first = pair[0];
  var second = pair[1];
  return first + second;
});

// This gives you:
// c = [5, 7, 9]
Run Code Online (Sandbox Code Playgroud)

工作范例: