JS 删除数组中某个元素的几种方式

作者: web 发布时间: 2023-02-04 浏览: 828 次 编辑

第一种:删除最后一个元素

pop 删除

var arr = [1,2,3,4,5]
arr.pop()

// arr => [1,2,3,4]

slice 删除

var arr = [1,2,3,4,5]
var new_arr = arr.slice(0, -1)

// arr => [1,2,3,4,5]

// new_arr => [1,2,3,4]

var arr = [1,2,3,4,5]
var new_arr = arr.slice(0, arr.length - 1)

// arr => [1,2,3,4,5]

// new_arr => [1,2,3,4]

splice 删除

var arr = [1,2,3,4,5]
var new_arr = arr.splice(-1)

// arr => [1,2,3,4]

// new_arr => [5]

var arr = [1,2,3,4,5]
var new_arr = arr.splice(-1, 1)

// arr => [1,2,3,4]

// new_arr => [5]

var arr = [1,2,3,4,5]
var new_arr = arr.splice(arr.length - 1)

// arr => [1,2,3,4]

// new_arr => [5]

var arr = [1,2,3,4,5]
var new_arr = arr.splice(arr.length - 1, 1)

// arr => [1,2,3,4]

// new_arr => [5]

for 删除

var arr = [1,2,3,4,5]
var new_arr = []
for (let i = 0, len = arr.length; i < len; i++) {
if (i < len - 1) {
new_arr.push(arr[i])
}
}

// arr => [1,2,3,4,5]

// new_arr => [1,2,3,4]

length 删除

var arr = [1,2,3,4,5]
arr.length = arr.length - 1

// arr => [1,2,3,4]

第二种: 删除第一个元素

shift 删除

var arr = [1,2,3,4,5]
arr.shift()

// arr => [2,3,4,5]

slice 删除

var arr = [1,2,3,4,5]
var new_arr = arr.slice(1)

// arr => [1,2,3,4,5]

// new_arr => [2,3,4,5]

splice 删除

var arr = [1,2,3,4,5]
var new_arr = arr.splice(0, 1)

// arr => [2,3,4,5]

// new_arr => [1]

第三种:删除数组中某个指定下标的元素

splice 删除

var delete_index = 2
var arr = [1,2,3,4,5]

// arr => [1,2,3,4,5]

var new_arr = arr.splice(delete_index, 1)

// new_arr => [3]

// arr => [1,2,4,5]

for 删除

var delete_index = 2,
arr = [1,2,3,4,5],
new_arr = []
for (let i = 0, len = arr.length; i < len; i++) {
if (i != delete_index) {
new_arr.push(arr[i])
}
}

// arr => [1,2,3,4,5]

// new_arr => [1,2,4,5]

注意:

1. 不可以使用 delete 方式删除数组中某个元素,此操作会造成稀疏数组,被删除的元素的为位置依然存在为empty,且数组的长度不变

2. 不可以使用 forEach 方法比对数组下标值,因为 forEach 在循环的时候是无序的

第四种:删除数组中某个指定元素的元素

splice 删除

var element = 2,
arr = [1,2,3,4,5]
arr.splice(arr.indexOf(2), 1)

// arr => [1,3,4,5]

filter 删除

var arr = [1,2,3,4,5],
element = 2
arr = arr.filter(item => item != element)

// arr => [1,3,4,5]

forEach、map、for 删除

var arr = [1,2,3,4,5],
element = 2,
new_arr = []
arr.forEach(item => (item != element && new_arr.push(item)))

// new_arr => [1,3,4,5]

// map 同理

var arr = [1,2,3,4,5],
element = 2,
new_arr = []
for (let i = 0; i < arr.length; i++) {
arr[i] != element && new_arr.push(arr[i])
}

// new_arr => [1,3,4,5]

Set 删除

var arr = [1,2,3,4,5],
element = 2
var new_set = new Set(arr)
new_set.delete(element)
var new_arr = [...new_set]

// new_arr => [1,3,4,5]