Is it possible to set the custom index of an array with a variable.
for example:
var indexID = 5;
var temp = {
indexID: new Array()
};
The above example sets the array index to indexID
and not 5
. I have tried using =
snd quotes but I without any success.
Thnaks
A great use of for loops is performing operations on elements in an array variable. The for loop can increment through the array's index values to access each element of the array in succesion.
Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes.
No, it doesn't make sense to use array to store values in a (string)key when you cannot use the string keys in methods like forEach , map and array related methods. It'll make things complicated but still if you want to do it then use an object instead.
Yes, just use square brackets notation:
var temp = {};
temp[indexID] = [];
Also pay attention to the fact that temp
is an object, and not an array. In JavaScript all associative arrays (or dictionaries) are represented as objects.
MORE: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId
I think what you want is:
var indexID = 5;
var temp = {};
temp[indexID] = "stuff"
With your code, you will create an object.
Instead you can do
var indexID = 5;
var temp = [];
temp[indexID] = [];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With