数组的方法 - 删除数组中的某个元素

1. splice 方法

数组的splice方法很强大,可以进行 删除增加替换 操作,同时会改变原数组,返回删除/替换掉的元素组成的新数组

  • 删除

    /* 删除下标为4的元素 */
    const arr = [1,2,3,4,5,6,7,8,9,10]
    const arrNew = arr.splice(4,1)
    console.log(arr, arrNew) // [1,2,3,4,6,7,8,9,10]     [5]
    
    /* 删除下标从4到6的元素 */
    const arr2 = [1,2,3,4,5,6,7,8,9,10]
    const arrNew2 = arr2.splice(4,3)
    console.log(arr2, arrNew2) // [1,2,3,4,8,9,10]     [5,6,7]
    
  • 增加

    /* 下标为4处 增加一个元素 'a' */
    const arr = [1,2,3,4,5,6,7,8,9,10]
    const arrNew = arr.splice(4,0,'a')
    console.log(arr, arrNew) // [1,2,3,4,'a',5,6,7,8,9,10]    []
    
    /* 下标为4处,增加 'b','c', 'd', 'e' 这4个元素 */
    const arr2 = [1,2,3,4,5,6,7,8,9,10]
    const arrNew2 = arr2.splice(4,0,'b','c','d','e')
    const arrNew3 = arr2.splice(4,0,...['b','c','d','e'])
    console.log(arr2, arrNew2) // [1,2,3,4,'b','c','d','e',5,6,7,8,9,10]     []
    
  • 替换

    /* 下标为4处元素,替换为 'a' */
    const arr = [1,2,3,4,5,6,7,8,9,10]
    const arrNew = arr.splice(4,1,'a')
    console.log(arr, arrNew) // [1,2,3,4,'a',6,7,8,9,10]    [5]
    
    /* 下标为4开始的元素,一次替换为 'b','c', 'd', 'e' 这4个元素 */
    const arr2 = [1,2,3,4,5,6,7,8,9,10]
    const arrNew2 = arr2.splice(4,4,'b','c','d','e')
    const arrNew3 = arr2.splice(4,4,...['b','c','d','e'])
    console.log(arr2, arrNew2) // [1,2,3,4,'b','c','d','e',9,10]     [5,6,7,8]
    

2. 删除下标为n的元素

const arr = [1,2,3,4,5,6,7,8,9,10]
const n = 4
const arrNew = arr.splice(4,1)
console.log(arr, arrNew)

3. 删除符合某些条件的元素

const arr = [
  { id: 1, cont: '1'},
  { id: 2, cont: '2'},
  { id: 3, cont: '3'},
  { id: 4, cont: '4'},
  { id: 5, cont: '5'}
]

删除id为3的元素

  • filter
  • findIdx + splice splice:会改变原数组
  • reduce
const arrNew = arr.filter(item => item.id !== 3)
const idx = arr.findIndex(item => item.id === 3)
arr.splice(idx, 1)
console.log(arr)
const arrNew2 = arr.reduce((total, current) => {
  current.id !== 3 && total.push(current)
	return total
}, [])
posted @ 2022-02-13 14:17  shine_lovely  阅读(3826)  评论(0编辑  收藏  举报