在 JavaScript 中删除数组元素 - 删除与拼接

新手上路,请多包涵

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

例如:

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

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

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

原文由 lYriCAlsSH 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 767
2 个回答

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

 > myArray = ['a', 'b', 'c', 'd']
 ["a", "b", "c", "d"]
 > delete myArray[0]
 true
 > myArray[0]
 undefined

请注意,它实际上并未设置为值 undefined ,而是从数组中删除了该属性,使其 看起来 未定义。 Chrome 开发工具通过在记录数组时打印 empty 来明确区分。

 > myArray[0]
 undefined
 > myArray
 [empty, "b", "c", "d"]

myArray.splice(start, deleteCount) 实际上删除元素,重新索引数组,并更改其长度。

 > myArray = ['a', 'b', 'c', 'd']
 ["a", "b", "c", "d"]
 > myArray.splice(0, 2)
 ["a", "b"]
 > myArray
 ["c", "d"]

原文由 Andy Hume 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

约翰的网站

原文由 Mohsen 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题