以下のコードスニペットを参照してください。
01 let array = [1, 2, 3, 4, 4, 5, 4, 4];
02 for (let i = 0; i < array.length; i++) {
03 if (array[i] === 4) {
04 array.splice(i, 1);
05 i--;
06 }
07 }
コード実行後の配列の値は何ですか?
正解:D
Comprehensive and Detailed Explanation:
The loop removes every 4:
* Start: [1, 2, 3, 4, 4, 5, 4, 4]
* i=0 # 1 (no change)
* i=1 # 2 (no change)
* i=2 # 3 (no change)
* i=3 # 4 # splice removes index 3 # [1,2,3,4,5,4,4], then i-- # 2
* Next loop, i=3 # 4 again # splice # [1,2,3,5,4,4], i-- # 2
* i=3 # 5 (no change)
* i=4 # 4 # splice # [1,2,3,5,4] , i-- # 3
* i=4 # 4 # splice # [1,2,3,5], i-- # 3
* Next i=4, array.length is 4 # loop ends.
All 4s removed, final array: [1, 2, 3, 5].