[JS Actual Combat] Add elements (add at specified locations)

Add element (add at specified location)

Insert picture description here

Method 1: Copy the first 0~index elements first, insert the item element, and then splice the elements after index

function insert(arr, item, index) {
    
    
  let newArr = arr.slice(0, index)
  newArr.push(item)
  newArr = newArr.concat(arr.slice(index))
  return newArr
}

Insert picture description here

Method 2: Insert using splice method (higher efficiency)

function insert(arr, item, index) {
    
    
  let newArr = arr.slice(0)
  newArr.splice(index,0, item)
  return newArr
}

Insert picture description here

Method 3: push.apply+splice

function insert(arr, item, index) {
    
    
  let newArr = [];
  [].push.apply(newArr,arr);
  newArr.splice(index,0, item);
  return newArr
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43352901/article/details/108372477