Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  176] [ 1]  / answers: 1 / hits: 103139  / 13 Years ago, fri, march 2, 2012, 12:00:00

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

More From » javascript

 Answers
15

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

[#87094] Thursday, March 1, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;