Keep in mind that using a proper position (or 0) index is essential for values to be placed accurately within the array:
var array = [];
array[0] = "Foo";
array[1] = "Bar";
// Result: ["Foo", "Bar"]
// Length: 2
If non-index values outside of the range 0-9+ are added, they will not be included in the array:
var array = [];
array[0] = "Foo";
array[1] = "Bar";
array[-1] = "Fizzbuzz"; // This is an incorrect array index - discard it
// Result: ["Foo", "Bar"]
// Length: 2
Values are only accepted within the array when the rules are followed. Any deviations are not recognized. However, such values can still be accessed on the Array object itself, as is common in JavaScript. Even if ["Foo", "Bar"]
are the sole values in our array, we can retrieve "Fizzbuzz"
:
array[-1]; // "Fizzbuzz"
It should be noted that this value is not part of the array values, given its invalid "index". It was simply appended as another member of the array. Other array members can be accessed similarly:
array["pop"]; // function pop() { [native code] }
In this case, the pop
method of the array is being accessed, indicating native code. No array values with a key of "pop" are retrieved, just a member of the array object. This distinction can be confirmed by iterating over the public members of the object:
for (var prop in array)
console.log(prop, array[prop]);
Upon running this loop, the following output is generated:
0 Foo
1 Bar
-1 Fizzbuzz
Hence, while the value exists on the object, it is not technically in the array.
Great question! Definitely made me take a second look.