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?
Use an object - with an integer as the key - rather than an array.
Try using an Object, not an Array:
Get the value for an associative array property when the property name is an integer:
Starting with an Associative Array where the property names are integers:
Push items to the array:
Loop through array and do something with the property value.
Console output should look like this:
As you can see, you can get around the associative array limitation and have a property name be an integer.
NOTE: The associative array in my example is the json you would have if you serialized a Dictionary<string, string>[] object.
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.
Compiling other answers:
Object
When using a number as a new property's key, the number turns into a string:
When accessing the property's value using the same number, the number is turned into a string again:
When getting the keys from the object, though, they aren't going to be turned back into numbers:
Map
ES6 allows the use of the Map object (documentation, a comparison with Object). If your code is meant to be interpreted locally or the ES6 compatibility table looks green enough for your purposes, consider using a Map:
No type conversion is performed, for better and for worse:
If the use-case is storing data in a collection then ES6 provides the
Map
type.It's only heavier to initialize.
Here is an example:
Result: