是否有可能在Underscore.js中同时遍历两个列表? [英] Is it possible to iterate through two lists at the same time in Underscore.js?
本文介绍了是否有可能在Underscore.js中同时遍历两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我基本上想用 _。each()
或 _。map()
in Underscore.js。
a = [1,2,3]
b = [3,2,1]
#结果列表
c = [0,0,0]
for i in [0 .. a.length - 1]
c [i] = a [i] + b [i]
这是在Matlab(我的主要语言)中也是如此:
$ b
c = arrayfun(@(x ,y)x + y,a,b)
直觉上,它感觉像Underscore中的语法应该be:
c = _.map(a,b,function(x,y){ return x + y;})
但是,该参数列表不可接受;第二个参数应该是一个可调用的函数。
在这种情况下,可选的context参数不会帮助我。
解决方案
使用 zip (也来自underscore.js)。像这样:
var a = [1,2,3];
var b = [4,5,6];
var zip = _.zip(a,b);
//这给你:
/ zipped = [[1,4],[2,5],[3,6]]
var c = _。 map(拉丁语,函数(pair)){
var first = pair [0];
var second = pair [1];
返回first + second;
});
//这会给你:
// c = [5,7,9]
工作示例:
I basically want to express the following behavior using _.each()
or _.map()
in 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]
This is definitely possible in Matlab (my primary language) as such:
c = arrayfun(@(x,y) x+y, a, b)
Intuitively, it feels like the syntax in Underscore should be:
c = _.map(a, b, function(x, y){ return x + y;})
However, that argument list isn't acceptable; the second parameter is supposed to be a callable function.
The optional "context" argument won't help me in this situation.
解决方案
Use zip (also from underscore.js) for that. Something like this:
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]
Working example:
这篇关于是否有可能在Underscore.js中同时遍历两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文