Array collapse problem + Optimal solution for array addition and deletion without considering sorting

The problem of array collapse, the judgment of the next digit of the deleted element is crossed, and the i-operation after the deletion needs to be performed to avoid skipping the element immediately after the deleted

let arr = [10,20,30,40]
for(let i=0;i<arr.length;i++){
    console.log(arr[i])
    if(i===1){
        arr.splice(i,1);
        i-- //使得数组不会坍陷
    }
}


Adding or deleting one element at a time will cause a large number of indexes to be reset . Optimization without considering the sorting situation: replace the last item with the element to be deleted and reduce the length of the array by one

let arr = [10,20,30,40]
arr[1] = arr[arr.length-1]
arr.length--
console.log(arr)
//[ 10, 40, 30 ]
Published 128 original articles · 52 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/weixin_44523860/article/details/105317334