Skip to content Skip to sidebar Skip to footer

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 kno

Solution 1:

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.

Solution 2:

You would use objects to do that:

var hash = {}
hash["foo"] = "foo";
hash.bar    = "bar";
// This is the dynamic approach: Your key is a string:
baz         = "baz"hash[baz]   = "hello";

To iterate, just use a for loop or $.each() in jQuery.

Solution 3:

use arrayName[var1+var2]

Note that arrayName.var is the same as arrayName["var"] -- it's just syntactic sugar. The second form is mostly used when dealing with the kind of problems that you are facing - dynamic object keys, and keys that are not alphanumeric (think of arrayName[".eval()"]; this is a perfectly legal object key that has nothing to do with the javascript eval() function)

Solution 4:

Are you looking for variableName = 'bla'+'foo'; arrayRef[variableName] = 'something'; ?

And even so, you should use an object literal instead. x = {}; x[variablename] = 'blah';

Solution 5:

You want a plain object with the same bracket notaiton here, like this:

var arrayName = {};
arrayName["indexName"] = value;

Post a Comment for "Variable As Index In An Associative Array - Javascript"