views:

156

answers:

3

I want to iterate over two arrays at the same time, as the values for any given index i in array A corresponds 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 populated as I print out the array prior to calling this, I haven't put all the other code in as it might be confusing, but if you think the problem is not evident from this I will edit the question:

//queryPredicates[] and queryObjects[] are defined above

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

Thanks

+2  A: 

If queryPredicates does not have numerical indexes, like 0, 1, 2, etc.. then trying to alert the value queryPredicates[0] when the first item has an index of queryPredicates['some_index'] won't alert anything.

Try using a 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]);
}
bschaeffer
Yeah thanks, I do understand that, my issue is trying to replicate iterating over two arrays simultaneously in a single loop when I don't use a numerical index. I think it might be as simple as trying to
Ankur
+8  A: 

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

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

In JavaScript the indexes are handled from 0 to length - 1.

Aside of that make sure that your two arrays have the same number of elements.

CMS
+1 - cross post.
BradBrening
Thanks, the reason I was starting with 1 was that I had a different problem earlier and somehow thought I had read that JS arrays start at 1 ... thanks for this. And then I just simply assumed I had this part correct.
Ankur
I can't believe I didn't pick this up! It's lucky that there are some people here that are thinking properly! ;)
Steve Harrison
+2  A: 

Arrays in JS are zero based. Length is the actual count. Your loop is going outside the bounds of the array.

BradBrening