在 Javascript 中,如何同时对两个 seq 的元素执行函数?
在 Javascript 中,同时迭代两个数组并在两个运行元素上调用函数的最佳方法是什么?例如:
var a = [1, 2, 3];
var b = [11, 12, 13];
function my_func() { /* some custom function */}
代码应该执行 my_func 3 次,如下所示:
my_func(1,11);
my_func(2,12);
my_func(3,13);
如何在不定义新函数但使用 jQuery/underscore api 的情况下实现这一目标?
In Javascript, what is the best way for iterating concurrently on two arrays and calling a function on the two running elements? For example:
var a = [1, 2, 3];
var b = [11, 12, 13];
function my_func() { /* some custom function */}
The code should execute my_func 3 times, like this:
my_func(1,11);
my_func(2,12);
my_func(3,13);
How can I achieve that without defining a new function, but using jQuery/underscore api?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
例如,这样(使用underscore.js)?
或者:
-
For example, this way (using underscore.js)?
Or:
-
嗯,直接的 JavaScript 非常擅长做到这一点。只需使用标准的 for 循环,假设您的 a 数组和 b 数组具有相同的长度。
jQuery 还提供了
.each()
方法,可以非常轻松地对一个序列进行操作。对两个进行操作只需要多一点代码。如果您想使用
zip
操作,则可以使用 jQueryArrayUtils 插件。作为 Python 的粉丝,最后一种方法对我来说似乎特别好。但老实说,如果您不打算做任何比调用 my_func 更复杂的事情,那么您也可以使用普通的 for 循环。
Well, straight-forward JavaScript is pretty good at doing this. Just use a standard
for
loop, assuming that youra
arrays andb
array have the same length.jQuery also provides an
.each()
method that can make operating on one sequence very easy. Operating on two just takes a bit more code.And if you want to use a
zip
operation, you can use the jQueryArrayUtils plugin.Being a fan of Python, this last method seems particularly nice to me. But honestly, if you're not going to do anything more complicated than calling
my_func
, then you may as well just use a normalfor
loop.jQuery 版本:
jQuery version: