[英]Infinite loop produced when shifting from and pushing in array
為什么以下代碼會導致無限循環?
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
while (arr.length > 0) {
console.log(arr.shift());
arr.push(arr.shift());
}
您在循環中要做的最后一件事是向數組添加一個項,這意味着數組長度將始終至少為1。即, arr.length > 0
始終為true
。
編輯 :添加示例以顯示正在發生的事情。 最終,當數組中沒有任何內容時, arr.shift()
計算結果為undefined
,然后將undefined
推回數組,從而使數組的長度為1個元素變長。 請參閱下面的控制台輸出。
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let i = 0; while (arr.length > 0 && i < 50) { arr.shift(); arr.push(arr.shift()); console.log(arr); i = i + 1; }
arr.shift()
在一個空數組上返回undefined
,因此一旦移出最后一個原始數字,您將得到undefined
,然后將其推回數組,因此數組永遠不會達到零長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.