[javascript] 使用 array.forEach 時若刪掉陣列元素,有些元素會被跳過去 Get link Facebook X Pinterest Email Other Apps - March 10, 2021 測試用程式碼 const array = [0,1,2,3] array.forEach((item, index) => { console.log('item:', item) array.splice(index, 1) }) console.log(array) 印出了 item: 0 item: 2 [ 1, 3 ] Read more
array = array.splice 以後,array 的值是什麼 Get link Facebook X Pinterest Email Other Apps - March 08, 2021 根據 Array.prototype.splice() - MDN ,array.splice(0, 1) 會從 array 中刪掉第 0 個元素,然後回傳 [被刪掉的元素]。那麼,執行完 array = array.splice 這行程式碼, array 會變成 被刪掉第 0 個元素 ,還是 [ 被刪掉的元素 ] 呢? 實驗1: let test = [0, 1] test = test.splice(0, 1) console.log(test) //印出來是[0] 實驗2: const test = [0, 1] test = test.splice(0, 1) console.log(test) 結果是 TypeError: Assignment to constant variable. 結論:test = test.splice(0, 1) 是把 test 賦值為 [被刪掉的元素]。這個結果非常正常。 Read more