Access javascript array "associative"

I have a simple simulated aarray with two elements:

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

I can access the value with this event:

 onclick="testButton00_('fruit')">with `testButton00_` function testButton00_(key){ var t = bowl[key]; alert("testButton00_: value = "+t); } 

However, whenever I try to access aarray from within the code using a key that is just an implicit string, I get undefined. Should I somehow pass the parameter with a shielded "key". Any ideas? TIA.

+6
javascript arrays associative
source share
3 answers

The key may be a dynamically calculated string. Give an example of what you pass on 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:

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

All of them have the same effect on the bowl object. And then you can use the appropriate patterns to retrieve the 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"]; 
+18
source share

I'm not sure I understand you, you can make sure that the key is a string like this

 if(!key) { return; } var k = String(key); var t = bowl[k]; 

Or you can check if the key exists:

 if( typeof(bowl[key]) !== 'undefined' ) { var t = bowk[key]; } 

However, I don’t think you posted any broken code?

0
source share

You can use JSON if you do not want to hide the key.

  var bowl = { fruit : "apple", nuts : "brazil" }; alert(bowl.fruit); 
0
source share

All Articles