在数组元素上使用delete运算符与使用array.splice方法有什么区别?
例如:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
如果我可以像删除对象那样删除数组元素,为什么还要使用拼接方法?
在数组元素上使用delete运算符与使用array.splice方法有什么区别?
例如:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
如果我可以像删除对象那样删除数组元素,为什么还要使用拼接方法?
当前回答
如果您的阵列较小,可以使用过滤器:
myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');
其他回答
delete将删除对象属性,但不会重新索引数组或更新其长度。这使得它看起来像是未定义的:
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined
请注意,它实际上没有设置为值undefined,而是从数组中删除了属性,使其看起来未定义。Chrome开发工具在记录阵列时打印为空,从而明确了这一区别。
> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]
splice(start,deleteCount)实际上删除了元素,重新索引数组,并更改其长度。
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]
应用delete运算符和splice()方法后,通过记录每个数组的长度可以看出差异。例如:
删除运算符
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5
delete运算符从数组中删除元素,但元素的“占位符”仍然存在。橡树已经被移除,但它仍然占用阵列中的空间。因此,阵列的长度保持为5。
拼接()法
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4
splice()方法完全删除目标值和“占位符”。橡树已经被移除,以及它在阵列中占据的空间。阵列的长度现在为4。
我在试图理解如何从数组中删除每一个元素时偶然发现了这个问题。这里是拼接和删除的比较,用于从项数组中删除每个“c”。
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
items.splice(items.indexOf('c'), 1);
}
console.log(items); // ["a", "b", "d", "a", "b", "d"]
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
delete items[items.indexOf('c')];
}
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
其他人已经正确比较了删除和拼接。
另一个有趣的比较是delete与undefined:一个被删除的数组项比一个刚刚设置为undefineed的数组项使用更少的内存;
例如,此代码不会完成:
let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
ary.push(y);
ary[y] = undefined;
y += 1;
}
console(ary.length);
它会产生以下错误:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
所以,正如您所看到的,undefined实际上占用了堆内存。
但是,如果您还删除了ary项(而不是将其设置为undefined),代码将缓慢完成:
let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
ary.push(x);
ary[x] = undefined;
delete ary[x];
x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);
这些都是极端的例子,但它们表明了我在任何地方都没有看到有人提到的删除。
我有两种方法。
简单的一个:
arr = arr.splice(index,1)
第二个:
arr = arr.filter((v,i)=>i!==index)
第二种方法的优点是可以删除一个值(所有值,而不是像大多数情况一样只删除第一个实例)
arr = arr.filter((v,i)=>v!==value)