我正在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[", e, "] =", a[e]);
print("a.length =", a.length);
for (var i = 0; i < a.length; i++)
print("\ta.hasOwnProperty(", i, ") =", 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 的)中,我读到数组的长度被计算为所有属性的最大数值。那么,当它拥有的最大数值属性是 0 时,为什么它说长度是 5?谢谢!