vote up 0 vote down star

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?

flag

5 Answers

vote up 7 vote down

You can just use an object:

var test = {}
test[2300] = 'Some string';
link|flag
vote up 3 vote down

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);
link|flag
1  
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 2 days ago
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 2 days ago
@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 2 days ago
vote up 3 vote down

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"]);
link|flag
+1 Note that this is even true of Arrays! see stackoverflow.com/questions/1450957/… – bobince 2 days ago
good point! i had forgotten about that. – Claudiu 2 days ago
vote up 1 vote down

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';
link|flag
vote up 0 vote down

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

link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.