Using an integer as a key in an associative array in JavaScript

user243540 picture user243540 · Jan 5, 2010 · Viewed 98.6k times · Source

When I create a new JavaScript array, and use an integer as a key, each element of that array up to the integer is created as undefined.

For example:

var test = new Array();
test[2300] = 'Some string';
console.log(test);

will output 2298 undefined's and one 'Some string'.

How should I get JavaScript to use 2300 as a string instead of an integer, or how should I keep it from instantiating 2299 empty indices?

Answer

Claudiu picture Claudiu · Jan 5, 2010

Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:

var test = {}
test[2300] = 20;
console.log(test["2300"]);