Fe-interview: [js] 第574天 写一个方法,批量删除指定索引的数组元素

Created on 9 Nov 2020  ·  1Comment  ·  Source: haizlin/fe-interview

第574天 写一个方法,批量删除指定索引的数组元素

3+1官网

我也要出题

js

Most helpful comment

保持索引:

function clearItems (list = [], indexes = []) {
  indexes.forEach(index => {
    list[index] !== undefined && (list[index] = undefined)
  })
}
var a = [1, 2, 3, 4, 5]
clearItems(a, [0, 1])
console.info(a) // [undefined, undefined, 3, 4, 5]

不保持索引

function clearItems (list = [], indexes = []) {
  indexes.sort((a, b) => b - a).forEach(index => {
    list.splice(index, 1)
  })
}
var a = [1, 2, 3, 4, 5, 6]
clearItems(a, [0, 2, 1])
console.info(a) // [4, 5, 6]

>All comments

保持索引:

function clearItems (list = [], indexes = []) {
  indexes.forEach(index => {
    list[index] !== undefined && (list[index] = undefined)
  })
}
var a = [1, 2, 3, 4, 5]
clearItems(a, [0, 1])
console.info(a) // [undefined, undefined, 3, 4, 5]

不保持索引

function clearItems (list = [], indexes = []) {
  indexes.sort((a, b) => b - a).forEach(index => {
    list.splice(index, 1)
  })
}
var a = [1, 2, 3, 4, 5, 6]
clearItems(a, [0, 2, 1])
console.info(a) // [4, 5, 6]
Was this page helpful?
0 / 5 - 0 ratings