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

例如:

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

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

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


当前回答

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

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

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

其他回答

function deleteFromArray(array, indexToDelete){
  var remain = new Array();
  for(var i in array){
    if(array[i] == indexToDelete){
      continue;
    }
    remain.push(array[i]);
  }
  return remain;
}

myArray = ['a', 'b', 'c', 'd'];
deleteFromArray(myArray , 0);

//结果:myArray=['b','c','d'];

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的网站

如果您的阵列较小,可以使用过滤器:

myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');

应用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。

保持简单:-

当您删除数组中的任何元素时,它将删除所述位置的值,并使其为空/未定义,但该位置存在于数组中。

var arr=[1,2,3,4,5];函数del(){删除arr[3];控制台日志(arr);}德尔(arr);

其中,与拼接原型一样,参数如下//arr.splice(开始删除的位置,要删除的项目数)

var arr=[1,2,3,4,5];函数spl(){arr.splice(0,2);//arr.splice(开始删除的位置,要删除的项目数)控制台日志(arr);}spl(arr);