js 數組插入和刪除處理


function insertArray(arr, val, compare, maxLen) {
  //返回位置
  const index = arr.findIndex(compare)
  if (index === 0) {
    return
  }
  if (index > 0) {
      //刪除一個
    arr.splice(index, 1)
  }
  //再插入(unshift() 方法可向數組的開頭添加一個或更多元素,並返回新的長度)
  arr.unshift(val)
  if (maxLen && arr.length > maxLen) {
      //pop() 方法用於刪除並返回數組的最后一個元素。
    arr.pop()
  }
}

 刪除

function deleteFromArray(arr, compare) {
  const index = arr.findIndex(compare)
  if (index > -1) {
    arr.splice(index, 1)
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM