It is common for project development to delete the value of the specified index in the array. The code is as follows:
let arr = [1, 2, 3, 4, 5, 6, 7, 8]
for(let i=0,len=arr.length; i < len-1; i++) {
if(i === 2) { // 删除索引为2的值
arr.splice(i, 1)
break
}
}
console.log(arr) // [1, 2, 4, 5, 6, 7, 8]
It can be seen from the above that deleting one can exit the sequence through break
, but how to delete multiple?
This is achieved?
let arr = [1, 2, 3, 4, 5, 6, 7, 8]
for(let i=0,len=arr.length; i < len-1; i++) {
if(arr[i] < 5) {
arr.splice(i, 1)
}
}
console.log(arr) // ?
The result: [2, 4, 5, 6, 7, 8], which is obviously not the desired data compared with the expected: [5, 6, 7, 8], why does this happen? Let's analyze the execution steps and output results of the next loop:
第1次arr[0]
,把符合条件的数组元素---9d875b1369bf141bf2d01118b5c81902---删除了,执行后, --- i
--- 1
, arr
变It became [2, 3, 4, 5, 6, 7, 8]
On the result of the first execution, execute again, it will delete ---d8340197a31a1bfb4554d542d3e33e55 arr[1]
, i
becomes 2
, arr
became [2, 4, 5, 6, 7, 8]
Then execute on the result of the second execution, there is no qualified condition, because arr[2]
is 5
, does not meet the conditions, arr is still [2, 4, 5, 6, 7, 8]
, So the execution result is wrong.
So how to solve it? We can take i
to deal with it, let i
0
--- every time, the code is as follows:
let arr = [1, 2, 3, 4, 5, 6, 7, 8]
for(let i=0,len=arr.length; i < len-1; i++) {
if(arr[i] < 5) {
arr.splice(i, 1)
i--
}
}
Summarize:
This is a typical problem that the execution result is incorrect due to the constant change of the original array. Therefore, in the process of processing the array, you should think more about where the current execution is in the array, so that the problem can be effectively found and solved.
For more front-end knowledge, please pay attention to the applet, there will be surprises from time to time!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。