【发布时间】:2010-01-21 11:00:11
【问题描述】:
为什么 JavaScript 返回错误的数组长度?
var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2
【问题讨论】:
标签: javascript arrays
为什么 JavaScript 返回错误的数组长度?
var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2
【问题讨论】:
标签: javascript arrays
【讨论】:
你必须使用 array.splice - 见http://www.w3schools.com/jsref/jsref_splice.asp
myarray.splice(0, 1);
这将删除第一个元素
【讨论】:
根据this docs,删除操作符不会改变数组的长度。您可以为此使用 splice()。
【讨论】:
来自 Array 的 MDC 文档:
"当你删除一个数组元素时, 数组长度不受影响。为了 例如,如果你删除 a[3],a[4] 是 仍然 a[4] 和 a[3] 是未定义的。这 即使您删除最后一个也保留 数组元素(删除 a[a.length-1])。”
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array
【讨论】:
您可以使用John Resig 的不错的 remove() 方法来做到这一点:
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);
【讨论】:
这是正常行为。 delete() 函数不会删除索引,只会删除索引的内容。因此,数组中仍有 2 个元素,但在索引 0 处,您将拥有 undefined。
【讨论】: