在JavaScript中删除数组元素-Delete与Splice

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

例如: ide

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

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

若是能够像删除对象同样删除数组元素,为何还要使用splice方法? ui


#1楼

在尝试了解如何从数组中删除元素的每次出现时,我偶然发现了这个问题。 这里有一个比较splicedelete去除每个'c'items阵列。 spa

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

#2楼

若是要迭代一个大数组并有选择地删除元素,则每次删除都调用splice()会很昂贵,由于splice()每次都必须从新索引后续元素。 因为数组在Javascript中是关联的,所以删除单个元素而后再从新索引数组会更有效。 .net

您能够经过构建一个新数组来作到这一点。 例如 code

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

可是我认为您不能修改原始数组中的键值,这样作会更有效-看起来您可能必须建立一个新数组。 对象

请注意,您不须要检查“未定义”条目,由于它们实际上并不存在,而且for循环不会返回它们。 这是阵列打印的结果,将其显示为未定义。 它们彷佛不存在于内存中。 索引

若是您可使用诸如slice()之类的更快的方法,可是它不会从新索引,那将是很好的。 有人知道更好的方法吗? ip


实际上,您可能能够按如下方式进行,这可能会更高效,更明智地执行如下操做: 内存

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)
},

#3楼

值得一提的是,拼接仅适用于数组。 (不能依赖对象属性遵循一致的顺序。)

要从对象中删除键值对,删除其实是您想要的:

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

#4楼

你能够用这样的东西

var my_array = [1,2,3,4,5,6]; delete my_array[4]; console.log(my_array.filter(function(a){return typeof a !== 'undefined';})); // [1,2,3,4,6]


#5楼

splice将与数字索引一块儿使用。

delete能够用于其余类型的索引。

例:

delete myArray['text1'];
相关文章
相关标签/搜索