亲宝软件园·资讯

展开

JS删除数组中某个元素的四种方式总结

ZHANG....... 人气:0

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

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]

pop 删除

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

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]

第二种:删除第一个元素

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]

shift 删除

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

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

filter 删除

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

splice 删除

var element = 2,
    arr = [1,2,3,4,5]
 
arr.splice(arr.indexOf(2), 1)
// 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]

第四种:删除数组中指定下标的元素

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 在循环的时候是无序的。

总结

加载全部内容

相关教程
猜你喜欢
用户评论