在数组元素上使用delete运算符与使用array.splice方法有什么区别?

例如:

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];
//  or
myArray.splice (1, 1);

如果我可以像删除对象那样删除数组元素,为什么还要使用拼接方法?


当前回答

最简单的方法可能是

var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
myArray = _.compact(myArray); ['a', 'c', 'd'];

希望这有帮助。参考:https://lodash.com/docs#compact

其他回答

其他人已经正确比较了删除和拼接。

另一个有趣的比较是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}.`);

这些都是极端的例子,但它们表明了我在任何地方都没有看到有人提到的删除。

如上多次所述,使用夹板()看起来非常合适。Mozilla文档:

splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。var myFish=['angel','小丑','普通话','鲟鱼'];myFish.splice(2,0,'鼓');//myFish是[“天使”、“小丑”、“鼓”、“普通话”、“鲟鱼”]myFish.splice(2,1);//myFish是[“天使”、“小丑”、“普通话”、“鲟鱼”]语法array.拼接(开始)array.spling(开始,删除计数)array.spling(start,deleteCount,item1,item2,…)参数开始开始更改阵列的索引。如果大于数组的长度,则实际起始索引将设置为数组的长度。如果是否定的,将从结尾开始许多元素。删除计数一个整数,指示要删除的旧数组元素的数量。如果deleteCount为0,则不会删除任何元素。在这种情况下,应至少指定一个新元素。如果deleteCount大于数组中从开始时剩余的元素数,则将删除数组末尾的所有元素。如果省略deleteCount,deleteCount将等于(arr.length-start)。项目1,项目2。。。要添加到数组的元素,从开始索引开始。如果不指定任何元素,splice()将只从数组中删除元素。返回值包含已删除元素的数组。如果只删除一个元素,则返回一个元素的数组。如果没有删除任何元素,则返回一个空数组。[...]

Array.remove()方法

jQuery的创建者John Resig创建了一个非常方便的Array.remove方法,我总是在项目中使用它。

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

下面是如何使用它的一些示例:

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

John的网站

好的,假设我们有下面这个数组:

const arr = [1, 2, 3, 4, 5];

让我们先删除:

delete arr[1];

结果是:

[1, empty, 3, 4, 5];

空的让我们来看看:

arr[1]; //undefined

所以意味着只是删除了值,现在它是未定义的,所以长度是相同的,也会返回true。。。

让我们重新设置阵列,这次使用拼接进行操作:

arr.splice(1, 1);

这是这次的结果:

[1, 3, 4, 5];

如您所见,数组长度已更改,arr[1]现在为3。。。

此外,这将返回数组中已删除的项目,在这种情况下为[3]。。。

拼接将使用数字索引。

而delete可以用于其他类型的索引。。

例子:

delete myArray['text1'];