目录
第一种:删除最后一个元素
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 = 2var 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]
今天的文章js 删除数组中某个元素的几种方式是什么_js delete删除数组元素[通俗易懂]分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/73953.html