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
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);
});
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]);
}
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]);
});
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.