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
According to the MDN JavaScript documentation you can define object literal property names using integers: Additionally, you can use a numeric or string literal for the name of a property.
{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.
Array properties also exist. These are properties that accept an index, just as an array does. The index can be one-dimensional, or multi-dimensional. In difference with normal (static or dynamic) arrays, the index of an array property doesn't have to be an ordinal type, but can be any type.
Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With