最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Array with number as property name - Stack Overflow

programmeradmin0浏览0评论
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

Share Improve this question edited Nov 2, 2011 at 1:21 Ben asked Nov 2, 2011 at 1:08 BenBen 13.7k4 gold badges50 silver badges70 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 4

The 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.

发布评论

评论列表(0)

  1. 暂无评论