Reputation: 2576
In the example below, the array2.length
is only 10
, while in my mind, it should be 13
.
Why does the "string keyed" indexes not increase the length
of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length
not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Upvotes: 69
Views: 110411
Reputation: 69934
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like []
or {}
instead of new Array
and new Object
.
Upvotes: 22
Reputation: 434
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length
Upvotes: 0
Reputation: 604
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
Upvotes: 2
Reputation: 754
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length
attribute of an array with a String, which is invalid.
Upvotes: 4
Reputation: 522125
Javascript arrays cannot have "string indexes". A Javascript Array
is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array
:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Upvotes: 143
Reputation: 5187
"string keyed" indexes are not indexes at all, but properties. array2["a"]
is the same as saying array2.a
. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
Upvotes: 3
Reputation: 41822
You're not adding items to the array; you're adding properties to the Array
object.
Upvotes: 12