简体   繁体   English

如何从数组中弹出所有元素

[英]How to pop all elements from an array

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.任何帮助将不胜感激。

Based on the documentation .pop() returns:根据文档.pop()返回:

The removed element from the array;从数组中移除的元素; undefined if the array is empty.如果数组为空,则undefined

So technically on each iteration the code removes the last element from the array which changes the .length property.所以从技术上讲,在每次迭代中,代码都会从数组中删除最后一个元素,这会改变.length属性。

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.如果您从后面读取数组,则for循环一起运行该块五次,这代表数组中的最后五个元素。 That's why you have 6,5,5,4,3 as an output.这就是为什么你有6,5,5,4,3作为 output。

I hope this clarifies!我希望这能澄清!

Can you change for to while loop?您可以将 for 更改for while循环吗? You would then console log all items然后,您将控制台记录所有项目

while(arr.length) {
    let item = arr.pop()
    console.log(item)
}

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:)您需要反转您的迭代,因为 case.pop 方法删除了最后一项,因此当从 0 迭代到最后一项时,您不会找到所有这些:)

 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) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM