在数组元素上使用 delete
运算符 与使用 Array.splice
方法有 什么区别?
例如:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
如果我可以像使用对象一样删除数组元素,为什么还要使用 splice 方法?
原文由 lYriCAlsSH 发布,翻译遵循 CC BY-SA 4.0 许可协议
在数组元素上使用 delete
运算符 与使用 Array.splice
方法有 什么区别?
例如:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
如果我可以像使用对象一样删除数组元素,为什么还要使用 splice 方法?
原文由 lYriCAlsSH 发布,翻译遵循 CC BY-SA 4.0 许可协议
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 许可协议
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
delete
将删除对象属性,但不会重新索引数组或更新其长度。这使它看起来好像是未定义的:请注意,它实际上并未设置为值
undefined
,而是从数组中删除了该属性,使其 看起来 未定义。 Chrome 开发工具通过在记录数组时打印empty
来明确区分。myArray.splice(start, deleteCount)
实际上删除元素,重新索引数组,并更改其长度。