admin管理员组文章数量:1334127
var myArray = new Array();
myArray['112'] = 0;
myArray.length
Why is length
113 in above sample? Shouldn't '112'
add a object property for the array and create something similar to myArray = {"112":0}
?
Besides this, why is the length 113 and not 1? Since myArray
actually only contains 1 value
var myArray = new Array();
myArray['112'] = 0;
myArray.length
Why is length
113 in above sample? Shouldn't '112'
add a object property for the array and create something similar to myArray = {"112":0}
?
Besides this, why is the length 113 and not 1? Since myArray
actually only contains 1 value
- 1 pshhhh....That's surprising. Learn something new everyday. – Itay Moav -Malimovka Commented Nov 2, 2011 at 1:10
- Because the length is always set to the largest positive integer property name plus one. The array only has one enumerable property, but it has a length of 113 (see ECMA-262 15.4). – RobG Commented Nov 2, 2011 at 1:28
4 Answers
Reset to default 4The array length
is one more than the highest index, so you get 113
.
No. The '112'
string and a pure numeric 112
evaluate to the same thing when JS is doing the array lookup, so you get a slot in the array rather than a property.
Simplest to think of a JS Array indexes as properties that happen to be numbers, even in string form. It's more chameleonic than you'd think at first.
But if you add a property with some nonnumeric name, like myArray['foo']
, it will do as you expect and the length won't change.
Consider this simple example:
var aa = [];
aa[3] = 'three';
alert( aa.length // 4
+ '\n' + aa[2] // undefined
+ '\n' + aa.hasOwnProperty('2') // false
);
The number 3 is used to assign the property name, but it is converted to a string and used as a standard property name (i.e. the string "3").
Adding a property named "3" has created one property and set the length to 4 since the length is always set to one more than the largest non-negative integer property name.
No other property is created, the array is "sparse", i.e. it doesn't have sequentially named (numbered) members. A for..in loop can also be used to see that there is only one property.
You got array of 0..112
elements - in total length of 113 elements.
本文标签: Javascript Array with number as property nameStack Overflow
版权声明:本文标题:Javascript Array with number as property name - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742358497a2459892.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论