Reputation: 11
var arr = [0,1,2,2,3,4,5,5,6];
for(let i = 0; i < arr.length; i++) {
let item = arr.pop()
console.log(item)
}
//Returns 6, 5, 5, 4, 3
I have no idea why this is returning only the numbers given instead of every number in the array. Any help would be greatly appreciated.
Upvotes: 0
Views: 3275
Reputation: 2829
You need to reverse your iteration, becuase .pop method removes the last item so when iterating from 0 to last item you will not find all of them :)
var arr = [0,1,2,2,3,4,5,5,6];
for(let i = arr.length; i > 0; i--) {
let item = arr.pop()
console.log(item)
}
Upvotes: 1
Reputation: 15166
Based on the documentation .pop()
returns:
The removed element from the array;
undefined
if the array is empty.
So technically on each iteration the code removes the last element from the array which changes the .length
property.
Probably a good representation what happens with the extended index from the loop:
var arr = [0,1,2,2,3,4,5,5,6];
for(let i = 0; i < arr.length; i++) {
let item = arr.pop()
console.log({i, item, length: arr.length});
}
All together for
loop was running the block five times which represents the last five elements from your array if you read the array from the back. That's why you have 6,5,5,4,3
as an output.
I hope this clarifies!
Upvotes: 1
Reputation: 11283
Can you change for
to while
loop?
You would then console log all items
while(arr.length) {
let item = arr.pop()
console.log(item)
}
Upvotes: 1