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

JavaScript

L神无Mandy

2020-03-09

是什么使用之间的差值delete算子阵列元件上,而不是使用Array.splice方法

例如:

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

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

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

第281篇《在JavaScript中删除数组元素-Delete与Splice》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

11个回答
Tony飞云 2020.03.09

IndexOf还接受引用类型。假设以下情况:

var arr = [{item: 1}, {item: 2}, {item: 3}];
var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]
var l = found.length;

while(l--) {
   var index = arr.indexOf(found[l])
      arr.splice(index, 1);
   }
   
console.log(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
梅JinJin十三 2020.03.09

delete:delete将删除对象属性,但不会为数组重新索引或更新其长度。这使得它看起来好像是未定义的:

splice:实际上删除元素,为数组重新索引,并更改其长度。

从最后删除元素

arrName.pop();

首先删除元素

arrName.shift();

从中间删除

arrName.splice(starting index,number of element you wnt to delete);

Ex: arrName.splice(1,1);

从最后删除一个元素

arrName.splice(-1);

使用数组索引号删除

 delete arrName[1];
泡芙十三 2020.03.09

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

  1. 使用splice()

    arrayObject.splice(index, 1);

  2. 使用删除

    delete arrayObject[index];

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

达蒙西里 2020.03.09

其他人已经比较正常delete使用splice

与另一个有趣的比较:deleteundefined被删除的数组项相比,删除的数组项使用的内存更少undefined;

例如,此代码不会完成:

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实际上占用了堆内存。

但是,如果您还是deleteary项目(而不是仅将其设置为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我从未见过有人提及的地方。

LEYJim 2020.03.09

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

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]在这种情况下...

ProStafan 2020.03.09

为什么不只是过滤?我认为这是在js中考虑数组的最清晰方法。

myArray = myArray.filter(function(item){
    return item.anProperty != whoShouldBeDeleted
});
阿飞米亚 2020.03.09

如果要迭代大数组并有选择地删除元素,则每次删除都调用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)
},
小哥西门 2020.03.09

删除拼接

当您从数组中删除项目时

var arr = [1,2,3,4]; delete arr[2]; //result [1, 2, 3:, 4]
console.log(arr)

当你拼接时

var arr = [1,2,3,4]; arr.splice(1,1); //result [1, 3, 4]
console.log(arr);

如果删除删除元素,索引保持为空

而在剪接元素被删除而其余元素索引相应减少的情况下

StafanStafan 2020.03.09

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

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

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

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

约翰的网站

L神无Mandy 2020.03.09

Core JavaScript 1.5参考>运算符>特殊运算符>删除运算符

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android