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

例如:

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

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

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


当前回答

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

其他回答

表演

关于功能差异,已经有很多很好的答案了——所以这里我想关注性能。今天(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的示例结果

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

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

如果您想要迭代一个大数组并选择性地删除元素,那么每次删除都调用splice()将非常昂贵,因为splice(()每次都必须重新索引后续元素。因为数组在Javascript中是关联的,所以删除单个元素然后重新索引数组会更有效。

您可以通过构建一个新阵列来实现这一点。例如

function reindexArray( array )
{
       var result = [];
        for( var key in array )
                result.push( array[key] );
        return result;
};

但我认为您不能修改原始数组中的键值,这会更有效——看起来您可能需要创建一个新数组。

请注意,您不需要检查“未定义”条目,因为它们实际上并不存在,for循环也不会返回它们。这是数组打印的产物,将它们显示为未定义。它们似乎不存在于记忆中。

如果您可以使用slice()之类的方法,这会很好,因为它会更快,但不会重新索引。有人知道更好的方法吗?


实际上,您可能可以按以下方式就地执行,这可能更高效、更具性能:

reindexArray : function( array )
{
    var index = 0;                          // The index where the element should be
    for( var key in array )                 // Iterate the array
    {
        if( parseInt( key ) !== index )     // If the element is out of sequence
        {
            array[index] = array[key];      // Move it to the correct, earlier position in the array
            ++index;                        // Update the index
        }
    }

    array.splice( index );  // Remove any remaining elements (These will be duplicates of earlier items)
},

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

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