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

例如:

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

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

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


当前回答

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

其他回答

表演

关于功能差异,已经有很多很好的答案了——所以这里我想关注性能。今天(2020.06.25),我对Chrome 83.0、Safari 13.1和Firefox 77.0进行了测试,以了解所提到的解决方案,以及所选答案

结论

拼接(B)解决方案适用于小型和大型阵列删除(A)解决方案对于大型阵列最快,对于小型阵列最快过滤器(E)解决方案在小阵列的Chrome和Firefox上速度最快(但在Safari上速度最慢,在大阵列上速度较慢)解决方案D很慢解决方案C不适用于Chrome和Safari中的大型阵列函数C(arr,idx){var rest=arr.slice(idx+1 | | arr.length);arr.length=idx<0?arr.length+idx:idx;arr.push.apply(arr,rest);返回arr;}//碰撞试验让arr=[…'abcdefghij'.repeat(100000)];//1M元件尝试{C(排列,1)}catch(e){console.error(e.message)}

细节

我对解决方案进行以下测试A.BCDE(我的)

对于小数组(4个元素)-您可以在这里运行测试对于大阵列(1M个元素)-您可以在这里运行测试

函数A(arr,idx){删除arr[idx];返回arr;}函数B(arr,idx){arr.splice(idx,1);返回arr;}函数C(arr,idx){var rest=arr.slice(idx+1 | | arr.length);arr.length=idx<0?arr.length+idx:idx;arr.push.apply(arr,rest);返回arr;}函数D(arr,idx){返回arr.slice(0,idx).contat(arr.slices(idx+1));}函数E(arr,idx){返回arr.filter((a,i)=>i!==idx);}myArray=[‘a’,‘b’,‘c’,‘d’];[A,B,C,D,E].map(f=>console.log(`${f.name}${JSON.stringify(f([…myArray],1))}`));此代码段仅显示使用过的解决方案

Chrome的示例结果

拼接将使用数字索引。

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

例子:

delete myArray['text1'];
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'];

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

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

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

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