I was wondering if there was anything special about javaScript's pop() function that I should know about.
My intention was to write a program that erases all of the values in an array, without actually deleting the array. My first attempt at that was this, which didn't exactly work out:
var index = [1,2,3,4,5,6,7,8,9,10];
for(var i=0;i<index.length;i++) { index.pop(); console.log(index+';'); }
// outputs this:
[1,2,3,4,5,6,7,8,9];
[1,2,3,4,5,6,7,8];
[1,2,3,4,5,6,7];
[1,2,3,4,5,6];
[1,2,3,4,5];
And then it simply stops there. Huh? Upon checking I found that the array really was [1,2,3,4,5]
, and not some console.log display error. Which didn't make sense.
On a hunch, I decided to decrement the for loop instead, and use it like this:
var index = [1,2,3,4,5,6,7,8,9,10];
for(var i=index.length; i--; i>0) { index.pop(); console.log(index+';'); }
// and for some reason, this works:
[1,2,3,4,5,6,7,8,9];
[1,2,3,4,5,6,7,8];
[1,2,3,4,5,6,7];
[1,2,3,4,5,6];
[1,2,3,4,5];
[1,2,3,4];
[1,2,3];
[1,2];
[1];
[];
So, why does the second example work and not the first? Seems pretty strange to me.
EDIT: I didn't know the for loop looked for index.length every time, not just the first time it was called.
The problem is that your first for loop is looking at the index.length. It is constantly changing because the array is getting smaller! So after five loops, your array is:
[1,2,3,4,5];
and i
is 5, because this is the fifth loop. So the condition i<index.length
comes out to 5<5
, which is false. Notice that the index.length
is only '5'! We've shortened the array! So, you leave the loop. If you want it to work, you'll need to store the original length in a variable so it doesn't change on you every iteration:
var original_length = index.length;
for(var i=0;i<original_length;i++) { index.pop(); console.log(index+';'); }
When you pop an item off the array the length of the array decreases, so when you've removed five elements from the array index.length
is five and i is five therefore the loop condition fails.
For the second loop you only check the length of the array at the begining before you remove elements from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With