Iterating jquery each loop for two arrays at once

后端 未结 4 1373
感动是毒
感动是毒 2020-12-10 14:30

I have two Javascript arrays of same size

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

I need to access the value of the two array in one e

相关标签:
4条回答
  • 2020-12-10 14:52

    Since they're the same size, just loop one, and reference the other with 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.

    $.each(demo.concat(demo3), function(i, item) {
        console.log(item);
    });
    
    0 讨论(0)
  • 2020-12-10 15:01

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

    for(var i = 0; i < demo.length; i++){
        console.log(demo[i]);
        console.log(demo3[i]);
    }
    
    0 讨论(0)
  • 2020-12-10 15:03

    Try using .concat if you want to joint iterate..

    $.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]);
    });
    
    0 讨论(0)
  • 2020-12-10 15:15

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

    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/

    _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.

    http://underscorejs.org/#zip

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

    0 讨论(0)
提交回复
热议问题