赞
踩
var arr = [1,2,3,4,5]
arr.pop()
// arr => [1,2,3,4]
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]
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]
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]
var arr = [1,2,3,4,5]
arr.length = arr.length - 1
// arr => [1,2,3,4]
var arr = [1,2,3,4,5]
arr.shift()
// arr => [2,3,4,5]
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]
var arr = [1,2,3,4,5]
var new_arr = arr.splice(0, 1)
// arr => [2,3,4,5]
// new_arr => [1]
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]
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]
注意:
不可以使用 delete 方式删除数组中某个元素,此操作会造成稀疏数组,被删除的元素的为位置依然存在为empty,且数组的长度不变
不可以使用 forEach 方法比对数组下标值,因为 forEach 在循环的时候是无序的
var element = 2,
arr = [1,2,3,4,5]
arr.splice(arr.indexOf(2), 1)
// arr => [1,3,4,5]
var arr = [1,2,3,4,5],
element = 2
arr = arr.filter(item => item != element)
// arr => [1,3,4,5]
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]
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]
转自:https://blog.csdn.net/Li_dengke/article/details/105249837
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。