why does shift stop my loop over this array

P

pantagruel

Hi,
I have an array like the following:

for(x=0;x<results.length;x++){

alert(results.length);
extracted=results.shift();

alert(results.length);
if(results.indexOf(extracted)== -1){

alert(extracted + "was 1")
}else{
alert(extracted + "was more than 1");
alert("here" + results.toString());
alert(results.length);
}
}

with a bunch of results in there. I loop over the results, starting at
8, outputting the number before the shift and the number after the
shift, when I get to the number after the shift = 4 then the indexOf
extracted in the array is obviously not -1 and I get the else, which
tells me that the index of my searchstring was more than 1, and that
the length of my results are 4. Then it stops looping.

This happens when I get to the first instance of a value that is
repeated in the array.

If I do the following

for(x=0;x<=results.length;x++){

alert(results.length);
extracted=results.shift();

alert(results.length);
alert(results.toString());
}

then the same thing happens. the last results toString() I get is

Sonia, me (2),Sonia, me (2),Sonia, me (2),Sonia, me (2)

each Sonia, me (2) is an individual item.

Thanks
 
G

Geoffrey Summerhayes

If I do the following

for(x=0;x<=results.length;x++){

alert(results.length);
extracted=results.shift();

alert(results.length);
alert(results.toString());

}

Commit this to memory as if it was from
Gargantua:

When writing an iterative loop on the
members of an array, NEVER call a mutator
on that array inside the loop or your code
will behave like flies on a dung heap,
erratic and buzzing all over the place.

[had to stick in a scatalogical ref. :)]

You forgot to put in an alert for x.
That will show you why it's not working
the way you expect it to.

Try this instead...

while(results.length>0){

alert(results.length);
extracted=results.shift();

alert(results.length);
alert(results.toString());

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top