在数组元素上使用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"]
​

其他回答

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

目前有两种方法可以做到这一点

使用夹板()arrayObject.spling(索引,1);使用deletedelete arrayObject[index];

但我始终建议对数组对象使用拼接,对对象属性使用删除,因为删除不会更新数组长度。

如果您想要迭代一个大数组并选择性地删除元素,那么每次删除都调用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)
},

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

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

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

拼接将使用数字索引。

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

例子:

delete myArray['text1'];