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

时间:2012-09-25 14:39:57

标签: javascript jquery

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

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

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

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

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

4 个答案:

答案 0 :(得分:18)

由于它们的大小相同,只需循环一个,然后用i引用另一个。

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

如果您不需要配对的索引,那么只需使用.concat背靠背运行它们。

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

答案 1 :(得分:9)

当然他们会保持相同的尺寸?使用好的'for

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

答案 2 :(得分:3)

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

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

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

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

答案 3 :(得分:0)

如果您尝试使用下划线(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]

});
​

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

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

http://underscorejs.org/#zip

所有这一切,在这种情况下,简单的for循环非常简单有效。