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

例如:

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

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

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


当前回答

如果要删除的元素位于中间(例如,我们要删除索引为1的“c”),可以使用:

var arr = ['a','b','c'];
var indexToDelete = 1;
var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))

其他回答

我有两种方法。

简单的一个:

arr = arr.splice(index,1)

第二个:

arr = arr.filter((v,i)=>i!==index)

第二种方法的优点是可以删除一个值(所有值,而不是像大多数情况一样只删除第一个实例)

arr = arr.filter((v,i)=>v!==value)

你可以用这样的东西

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

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

最简单的方法可能是

var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
myArray = _.compact(myArray); ['a', 'c', 'd'];

希望这有帮助。参考:https://lodash.com/docs#compact

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

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

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