【问题标题】:In Javascript, how to execute a function on elements of two seqs concurently?在 Javascript 中,如何同时对两个序列的元素执行函数?
【发布时间】:2023-03-07 19:36:01
【问题描述】:

在 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 的情况下实现这一点?

【问题讨论】:

  • 您知道[1 2 3][11 12 13] 不是有效的javascript 语法吗?如果您打算将它们作为数字数组,则需要在元素之间使用逗号。
  • 谢谢@jfriend00。那些日子里,我经常在 javascript 和 clojure(我最喜欢的两种语言)之间切换。

标签: javascript jquery iteration loops underscore.js


【解决方案1】:

比如这种方式(使用underscore.js)?

_.each( _.zip(a,b), my_func );

function my_func( pair ){
  alert( pair[0] + pair[1] );
}

或者:

_.each( _.zip(a,b), function( pair ){
  my_func( pair[0], pair[1] );
  // or: my_func.apply( null, pair );
});

function my_func( a, b ){
  alert( a + b );
}

-

function wrapply( func, thisObj ){
  return function( args ){
    return func.apply( thisObj, args );
  }
}

var add = wrapply( function(a,b){ return a+b; });
alert( add([1,2]) );

【讨论】:

  • 我真的很喜欢使用 apply 的代码。是否有任何其他 jQuery/下划线方法可以克服应用的需要。我的意思是这样写: .each_apply(.zip(a,b), my_func);
  • 嗨,我为此添加了一个示例函数,测试它是你的功课:)
【解决方案2】:

嗯,直接的 JavaScript 非常擅长做这件事。只需使用标准的for 循环,假设您的a 数组和b 数组具有相同的长度。

for (var i = 0; i < a.length; i++) {
    my_func(a[i], b[i]);
}

jQuery 还提供了一个.each() 方法,可以非常轻松地对one 序列进行操作。对两个进行操作只需要多一点代码。

$.each(a, function(i, aItem) { my_func(aItem, b[i]); });

如果你想使用zip操作,你可以使用jQueryArrayUtils plugin

$.zip(a, b).each(function() {
    var aItem = this[0];
    var bItem = this[1];
    my_func(aItem, bItem);
});

作为 Python 的粉丝,最后一种方法对我来说似乎特别好。但老实说,如果你不打算做任何比调用my_func 更复杂的事情,那么你还不如使用普通的for 循环。

【讨论】:

  • +1。我认为普通的for 循环是这里最好的方法。与基于库的解决方案一样易于编写和阅读(比 jQuery $.each() 方法更容易),并且在运行时更高效...
【解决方案3】:
[1,2,3].forEach(function(e, i, arr){my_func(e, arr[i]);}, [11,12,13]);

jQuery 版本:

$.each(a, function(index, value) { 
    my_func(value, b[index]);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多