javascript 一次为两个数组迭代 jquery 每个循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12585344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:35:23  来源:igfitidea点击:

Iterating jquery each loop for two arrays at once

javascriptjquery

提问by Priya

I have two Javascript arrays of same size

我有两个相同大小的 Javascript 数组

var demo=new Array();
var demo3=new Array();

I need to access the value of the two array in one each loop in JQuery code.After surfing for a while I came across zip operation and I tried using the code

我需要在 JQuery 代码中的每个循环中访问两个数组的值。冲浪一段时间后,我遇到了 zip 操作,我尝试使用代码

$.zip(demo,demo3).each(function(){                                   
    alert("demo "+this[0]);
    alert("demo3 "+this[1]);      
});

However this code does not work.Please help.

但是此代码不起作用。请帮助。

回答by I Hate Lazy

Since they're the same size, just loop one, and reference the other with i.

由于它们的大小相同,只需循环一个,并使用i.

$.each(demo, function(i, item) {
    console.log(demo[i], demo3[i]);
});

If you don't need the indices paired, then just run them back to back by using .concat.

如果您不需要配对的索引,则只需使用.concat.

$.each(demo.concat(demo3), function(i, item) {
    console.log(item);
});

回答by moonwave99

Sure they'll keep same size? Use a good ol' for:

确定他们会保持相同的大小?使用一个好的 ol' for

for(var i = 0; i < demo.length; i++){
    console.log(demo[i]);
    console.log(demo3[i]);
}

回答by Selvakumar Arumugam

Try using .concatif you want to joint iterate..

.concat如果要联合迭代,请尝试使用..

$.each(demo.concat(demo3), function (idx, el) {
     alert(el);
});

else simply iterate the array and use the index to access next..

否则只需迭代数组并使用索引访问下一个..

$.each(demo, function (idx, el) {
     alert(el);
     alert(demo3[idx]);
});

回答by lucuma

If you are trying to use the zip functionality from underscore (http://underscorejs.org/#zip) you can do the following:

如果您尝试使用下划线 (http://underscorejs.org/#zip) 的 zip 功能,您可以执行以下操作:

var combined = _.zip(demo, demo3);
$.each(combined, function(index, value) {
    // value[0] is equal to demo[index]
    // value[1] is equal to demo3[index]

});
?

Demo: http://jsfiddle.net/lucuma/jWbFf/

演示:http: //jsfiddle.net/lucuma/jWbFf/

_zip Documentation: Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes. If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion.

_zip 文档:将每个数组的值与相应位置的值合并在一起。当您拥有通过匹配数组索引进行协调的单独数据源时很有用。如果您正在使用嵌套数组的矩阵, zip.apply 可以以类似的方式转置矩阵。

http://underscorejs.org/#zip

http://underscorejs.org/#zip

All that said, a plain for loop is quite easy and efficient in this case.

综上所述,在这种情况下,一个普通的 for 循环非常简单和高效。