Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array with custom variable indexing

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

like image 587
Alan A Avatar asked May 20 '13 09:05

Alan A


People also ask

Can array index be a variable?

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.

Can you index a JavaScript array?

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.

Does array support string indexing in JavaScript?

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.


3 Answers

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

like image 188
VisioN Avatar answered Nov 03 '22 05:11

VisioN


I think what you want is:

var indexID = 5;
var temp = {};
temp[indexID] = "stuff"
like image 33
Nick Fishman Avatar answered Nov 03 '22 07:11

Nick Fishman


With your code, you will create an object.

Instead you can do

var indexID = 5;
var temp = [];
temp[indexID] = [];
like image 1
pvorb Avatar answered Nov 03 '22 07:11

pvorb