Why does a string index in an array not increase the 'length'?

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 = "";



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' };

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.


You're not adding items to the array; you're adding properties to the Array object.


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


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.


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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.