[Super detailed~] Detailed explanation of the splice function of js

splice

Will change the data of the original array

1.splice(index) a value

let arr = [23,34,55,90]
let arr1 = arr.splice(2)
//会改变原数组,从arr索引为2的位置开始其后面的都删除,返回的是移除的所有元素所构成的新数组
//所以arr为[23,34],arr1为[55,90]

2.splice(index, length) two values

let arr = [23,34,55,90]
let arr1 = arr.splice(1,1)
//会改变原数组,从arr索引为1的位置开始删除1个值,返回的是移除的所有元素所构成的新数组
//所以arr为[23,55,90],arr1为[34]

3.splice(index, length, value) three values

value is the inserted value

let arr = [23,34,55,90]
let arr1 = arr.splice(1,2,88)
//会改变原数组,从arr索引为1的位置开始删除2个值,删除的元素用88来代替,返回的是移除的所有元素所构成的新数组
//所以arr为[23,88,90],arr1为[34,55]

Note: So a pure insert element method is derived

Just pass the length parameter as 0, but note that the insertion position is inserted at the index position (or inserted in front of this position), and the remaining elements are moved backwards!

//有一个从小到大排序的数组,插入一个新的数据,保持原有的排序方式不变
//例:let arr = [2,5,6,9,12,34,56],要插入数字17
const insertItem = (val) => {
    
    
    for(i = 0; i < arr.length; i++){
    
    
        if(arr[i] > val){
    
    
            arr.splice(i, 0, val)
            break
        }
    }
}
insertItem(17)
//最终arr为[2,5,6,9,12,17,34,56]

Summarize

So splice can remove elements, insert elements, and replace elements at specified positions, which is a universal method

arr.push(val) = arr.splice(-1, 0, val)

Guess you like

Origin blog.csdn.net/m0_58768224/article/details/130016575