我在ideone中尝试以下代码:
var a = []; a[0] = 0; a[5] = 5; a[6] = undefined; print("contents before popping:"); for(var e in a) print("\ta[",e,"] =",a[e]); print("a.length =",a.length); for (var i = 0; i < a.length; i++) print("\ta.hasOwnProperty(",i,") =",a.hasOwnProperty(i)); print("popping -->",a.pop()); print("popping -->",a.pop()); print("contents after popping:"); for(var e in a) print("\ta[",a.hasOwnProperty(i));
输出如下:
contents before popping: a[ 0 ] = 0 a[ 5 ] = 5 a[ 6 ] = undefined a.length = 7 a.hasOwnProperty( 0 ) = true a.hasOwnProperty( 1 ) = false a.hasOwnProperty( 2 ) = false a.hasOwnProperty( 3 ) = false a.hasOwnProperty( 4 ) = false a.hasOwnProperty( 5 ) = true a.hasOwnProperty( 6 ) = true popping --> undefined popping --> 5 contents after popping: a[ 0 ] = 0 a.length = 5 a.hasOwnProperty( 0 ) = true a.hasOwnProperty( 1 ) = false a.hasOwnProperty( 2 ) = false a.hasOwnProperty( 3 ) = false a.hasOwnProperty( 4 ) = false
在我的JavaScript书中(好吧,Crockford’s),我读到数组的长度被计算为所有属性的最大数值.那么,为什么它的最大数值属性为0时长度为5?谢谢!
解决方法
关于Javascript的一个好处是它的语义是正式的,并且尽可能明确地在标准中定义.具体来说,section 15.4表示:
The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed,other properties are adjusted as necessary to maintain this invariant.
换句话说,每次更改数组时,都会调整其长度,但是,它只能保证大于max(索引),并且不一定等于max(索引)1.例如,pop method总是删除长度 – 无论数组实际包含多少元素,第1个元素并将长度减1.
另请注意,大多数数组方法都是通用的,并且不会“专门”了解有关数组的任何信息.它们可以操纵任意对象,如果这样的对象碰巧有一个名为length的属性,它将根据上述规则进行调整.考虑:
foo = { length: 100,99: 'hi' } alert([].pop.apply(foo)) // hi alert(foo.length) // 99 alert([].pop.apply(foo)) // undefined alert(foo.length) // 98
也就是说,在您的问题的上下文中,如何准确表示数组是无关紧要的 – pop和朋友不使用此信息.