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

例如:

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

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

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


当前回答

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'];

其他回答

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

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

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

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

myArray = myArray.filter(function(item){
    return item.anProperty != whoShouldBeDeleted
});

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

delete的行为类似于非真实情况,它只是删除项,但数组长度保持不变:

来自节点终端的示例:

> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]

这里有一个函数,使用slice()按索引删除数组中的项,它将arr作为第一个参数,将要删除的成员的索引作为第二个参数。如您所见,它实际上删除了数组的成员,并将数组长度减少1

function(arr,arrIndex){
    return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}

上面的函数所做的是将索引之前的所有成员和索引之后的所有成员连接在一起,并返回结果。

下面是一个使用上述函数作为节点模块的示例,查看终端将非常有用:

> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4 
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3

请注意,这不会在一个数组中使用重复数据,因为indexOf(“c”)只会得到第一次出现,并且只会拼接并删除它找到的第一个“c”。