Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable as index in an associative array - Javascript

I'm trying to create an associative array, create an empty array, and then add a (indexName -> value) pair:

var arrayName = new Array;  arrayName["indexName"] = value;  // i know i can also do the last line like this:  arrayName.indexName = value; 

When I assign the value to the indexName I want indexName to be dynamic and the value of a variable. So I tried this:

arrayName[eval("nume")] = value; 

Where:

var var1 = "index"; var var2 = "Name";  var nume = '"' + var1 + var2 + '"';  

but: alert(arrayName["indexName"]); doesn't return "value"... it says "undefined"

Is there something I’m missing? (I’m not familiar with eval() ); if the way I’m trying is a dead end, is there another way to make the index name of the associative array value dynamic?

like image 555
bogdan Avatar asked Nov 03 '10 20:11

bogdan


People also ask

Can you index a JavaScript array?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .

Can you put variables in an array JavaScript?

Array Elements Can Be ObjectsJavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.

How can we define an associative array and assign a value to it?

Definition and Usage In PHP, an array is a comma separated collection of key => value pairs. Such an array is called Associative Array where value is associated to a unique key. The key part has to ba a string or integer, whereas value can be of any type, even another array. Use of key is optional.

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.


1 Answers

At first I don't think you need a real array object to do what you need, you can use a plain object.

You can simply use the bracket notation to access a property, using the value of a variable:

var obj = {}; var nume = var1 + var2; obj[nume] = value; 

Array's are simply objects, the concept of an "associative array" can be achieved by using a simple object, objects are collections of properties that contain values.

True arrays are useful when you need to store numeric indexes, they automatically update their length property when you assign an index or you push a value to it.

like image 84
Christian C. Salvadó Avatar answered Sep 21 '22 04:09

Christian C. Salvadó