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

例如:

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

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

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


当前回答

删除Vs接头

从数组中删除项时

var arr=[1,2,3,4];删除arr[2]//结果[1,2,3:,4]控制台日志(arr)

当您拼接时

var arr=[1,2,3,4];arr.splice(1,1)//结果[1,3,4]控制台日志(arr);

如果删除,元素将被删除,但索引仍为空

而在拼接元件被删除的情况下,其余元件的索引相应地减少

其他回答

可能还值得一提的是,拼接仅适用于阵列。(不能依赖对象财产来遵循一致的顺序。)

要从对象中删除键值对,实际上需要删除:

delete myObj.propName;     // , or:
delete myObj["propName"];  // Equivalent.

我在试图理解如何从数组中删除每一个元素时偶然发现了这个问题。这里是拼接和删除的比较,用于从项数组中删除每个“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可以用于其他类型的索引。。

例子:

delete myArray['text1'];

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"]

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