Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript "associative" array access

I have a simple simulated array with two elements:

bowl["fruit"] = "apple";
bowl["nuts"] = "brazilian";

I can access the value with an event like this:

onclick = "testButton00_('fruit')">with `testButton00_`

function testButton00_(key){
    var t = bowl[key];
    alert("testButton00_: value = "+t);
}

However, whenever I try to access the array from within code with a key that is just a non-explicit string, I get undefined. Do I have somehow have to pass the parameter with the escaped 'key'?

like image 376
cp. Avatar asked Mar 26 '10 15:03

cp.


1 Answers

The key can be a dynamically computed string. Give an example of something you pass that doesn't work.

Given:

var bowl = {}; // empty object

You can say:

bowl["fruit"] = "apple";

Or:

bowl.fruit = "apple"; // NB. `fruit` is not a string variable here

Or even:

var fruit = "fruit";
bowl[fruit] = "apple"; // now it is a string variable! Note the [ ]

Or if you really want to:

bowl["f" + "r" + "u" + "i" + "t"] = "apple";

Those all have the same effect on the bowl object. And then you can use the corresponding patterns to retrieve values:

var value = bowl["fruit"];
var value = bowl.fruit; // fruit is a hard-coded property name
var value = bowl[fruit]; // fruit must be a variable containing the string "fruit"
var value = bowl["f" + "r" + "u" + "i" + "t"];
like image 52
Daniel Earwicker Avatar answered Sep 19 '22 07:09

Daniel Earwicker