0

I think it should alert 4 times, but why it just alerted just 2 times. Is there anyone can make an explanation for me?

   var arr = new Array;

   arr.push("1");
   arr.push("2");
   arr.push("3");
   arr.push("4");

   for(var i=0;i<arr.length;i++){
     alert(arr.pop());
   }

4 Answers 4

6

Change your for loop to a while loop:

while(arr.length) {
    alert(arr.pop());   
}

The problem is that you remove elements from the array, so the length decreases, ending your for loop early. After 2 iterations of your for loop, arr.length is 2, and i is also 2, so the loop ends.

Here's a working example of the above.

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent! I'm really a novice of programming
or another possibility is doing a for(var i = 0, l = arr.length; i < l; i++)
1

Your code is checking length every Loop so in second loop array length must be 2 (2 poped) but var i is 2 so they'll out loop

Try to use for or you can use

var arr = new Array;

arr.push("1");
arr.push("2");
arr.push("3");
arr.push("4");
var length = arr.length;
for(var i=0;i<length;i++){
    alert(arr.pop());
}

Comments

0

Pop removes the element from the array, and decreases the length property. So after two loop i = 2 and the array length = 2.

   var arr = new Array;
   arr.push("1");
   arr.push("2");
   arr.push("3");
   arr.push("4");
   var len = arr.length;
   for(var i=0;i<len;i++){
       alert(arr.pop());
   }

Comments

0

due to pop() operation array length decrements during loop execution. So after 2 iterations, i==2 and arr.length==2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.