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

例如:

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

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

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


当前回答

从核心JavaScript 1.5参考>运算符>特殊运算符>删除运算符:

删除数组元素时数组长度不受影响。对于例如,如果删除[3],则[4]为仍然a[4]和a[3]未定义。这即使删除最后一个数组的元素(删除a[a.length-1])。

其他回答

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

如上多次所述,使用夹板()看起来非常合适。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()将只从数组中删除元素。返回值包含已删除元素的数组。如果只删除一个元素,则返回一个元素的数组。如果没有删除任何元素,则返回一个空数组。[...]

删除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);

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

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

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

IndexOf也接受引用类型。假设以下场景:

var arr=[{项:1},{项2},{项3}];var发现=发现(2,3)//伪代码:将返回〔{item:2},{item:3}〕var l=基础长度;而(l-){var索引=arr.indexOf(找到[l])arr.splice(索引,1);}控制台日志(arr.length)//1.

不同之处:

var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
  while(!found && l--) {
  found = arr[l] === item2;
}

console.log(l, arr[l]);// l is index, arr[l] is the item you look for