Iterate over two arrays at a time in Javascript

I want to iterate over two arrays at the same time, since the values ​​for any given index i in array A correspond to the value in array B.

I am currently using this code and getting undefined when I call alert(queryPredicates[i]) or alert(queryObjects[i]) .
I know my array is populating when I print the array before calling this.

 //queryPredicates[] and queryObjects[] are defined above as global vars - not in a particular function, and I have checked that they contain the correct information. function getObjectCount(){ var variables = queryPredicates.length; //the number of variables is found by the length of the arrays - they should both be of the same length var queryString="count="+variables; for(var i=1; i<=variables;i++){ alert(queryPredicates[i]); alert(queryObjects[i]); } 
+4
source share
3 answers

The value of the length property of any array is the actual number of elements (more precisely, the largest existing index plus one).

If you try to access this index, it will always be undefined because it is outside the bounds of the array (this happens in the last iteration of your loop, because the condition is i<=variables ).

In JavaScript, indexes are processed from 0 to length - 1 .

Also, make sure your two arrays have the same number of elements.

+10
source

If queryPredicates does not have numerical indices, such as 0, 1, 2, etc., then when you try to notify the value of queryPredicates[0] , when the first element has the index queryPredicates['some_index'] , nothing will be warned.

Try using the for loop instead:

 stuff['my_index'] = "some_value"; for (var i in stuff) { // will alert "my_index" alert(i); // will alert "some_value" alert(stuff[i]); } 
+3
source

Arrays in JS are zero based. Length is the actual quantity. Your loop goes beyond the array.

+2
source

Source: https://habr.com/ru/post/1309230/


All Articles