views:

312

answers:

5

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 instanciating 2299 empty indices?

+8  A: 

You can just use an object:

var test = {}
test[2300] = 'Some string';
Annie
+1  A: 

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';
Jeff Hammerbacher
+3  A: 

Use an object instead of an array. Arrays in JavaScript are not associative arrays. They are objects with magic associated with any properties whose names look like integers. That magic is not what you want if you're not using them as a traditional array-like structure.

var test = {};
test[2300] = 'some string';
console.log(test);
bdukes
They *can* be associative arrays, but only because they are also objects which can have named properties set. But this just makes things ridiculously confusing, and so yes, objects are much better to use.
Graza
Arrays can never be associative Graza. If you try to use keys in an array and then iterate over them you'll notice you're also iterating through all the default methods and properties of arrays -> not very desirable.
Swizec Teller
@Swizec - exactly why I said "ridiculously confusing". You *can* use an array as an associative array - that is as name/value pairs, but you would never want to iterate them! (I was simply pointing out a technicality, definitely not something I would at all recommend doing)
Graza
A: 

Use an object - with an integer as the key - rather than an array.

Upper Stage
+3  A: 

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"]);
Claudiu
+1 Note that this is even true of Arrays! see http://stackoverflow.com/questions/1450957/pythons-json-module-converts-int-dictionary-keys-to-strings#1450981
bobince
good point! i had forgotten about that.
Claudiu