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

其他回答

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

拼接将使用数字索引。

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

例子:

delete myArray['text1'];

如上多次所述,使用夹板()看起来非常合适。Mozilla文档:

splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。var myFish=['angel','小丑','普通话','鲟鱼'];myFish.splice(2,0,'鼓');//myFish是[“天使”、“小丑”、“鼓”、“普通话”、“鲟鱼”]myFish.splice(2,1);//myFish是[“天使”、“小丑”、“普通话”、“鲟鱼”]语法array.拼接(开始)array.spling(开始,删除计数)array.spling(start,deleteCount,item1,item2,…)参数开始开始更改阵列的索引。如果大于数组的长度,则实际起始索引将设置为数组的长度。如果是否定的,将从结尾开始许多元素。删除计数一个整数,指示要删除的旧数组元素的数量。如果deleteCount为0,则不会删除任何元素。在这种情况下,应至少指定一个新元素。如果deleteCount大于数组中从开始时剩余的元素数,则将删除数组末尾的所有元素。如果省略deleteCount,deleteCount将等于(arr.length-start)。项目1,项目2。。。要添加到数组的元素,从开始索引开始。如果不指定任何元素,splice()将只从数组中删除元素。返回值包含已删除元素的数组。如果只删除一个元素,则返回一个元素的数组。如果没有删除任何元素,则返回一个空数组。[...]

从核心JavaScript 1.5参考>运算符>特殊运算符>删除运算符:

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