javascript “associative” array access

久未见 提交于 2019-11-30 12:58:46

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"];

I am not sure I understand you, you can make sure 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 have posted the non working code?

You could use JSON if you dont want to escape the key.

 var bowl = {
  fruit : "apple",
  nuts : "brazil"
 };

alert(bowl.fruit);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!