-
心有法竹
delete将删除对象属性,但不会重新索引数组或更新其长度。这使它看起来似乎是未定义的:> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]> delete myArray[0]
true> myArray[0]
undefined注意,它实际上没有设置为undefined,而是将属性从数组中移除,使其成为出现没有定义。Chrome dev工具通过打印明确了这一区别。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"]
-
肥皂起泡泡
Array.emove()方法约翰·雷西格,jQuery的创建者创建了一个非常方便的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 arrayarray.remove(1);// Remove the second-to-last item from the arrayarray.remove(-2);
// Remove the second and third items from the arrayarray.remove(1,2);
// Remove the last and second-to-last items from the arrayarray.remove(-2,-1);约翰网站
-
元芳怎么了
因为DELETE只从数组中的元素中删除对象,所以数组的长度不会改变。Splice移除对象并缩短数组。下面的代码将显示“a”、“b”、“未定义”、“d”myArray = ['a', 'b', 'c', 'd']; delete myArray[2];for (var count = 0; count < myArray.length; count++) {
alert(myArray[count]);}而这将显示“a”、“b”、“d”myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);for (var count = 0; count < myArray.length; count++) {
alert(myArray[count]);}
-
温温酱
我无意中发现了这个问题,同时试图理解如何从Array中删除每个元素的出现。下面是一个比较的splice和delete为了移除每一个'c'从items阵列。var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];while (items.indexOf('c') !== -1) {
items.splice(items.indexOf('c'), 1);}console.log(items);
// ["a", "b", "d", "a", "b", "d"]items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];while (items.indexOf('c') !== -1) {
delete items[items.indexOf('c')];}console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]