JavaScript “associative” array access

前端 未结 3 1268
一生所求
一生所求 2021-01-02 01:21

I have a simple simulated array with two elements:

bowl["fruit"] = "apple";
bowl["nuts"] = "brazilian";
相关标签:
3条回答
  • 2021-01-02 01:27

    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?

    0 讨论(0)
  • 2021-01-02 01:35

    You could use JSON if you don’t want to escape the key:

    var bowl = {
      fruit: "apple",
      nuts: "brazil"
    };
    
    alert(bowl.fruit);
    
    0 讨论(0)
  • 2021-01-02 01:40

    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"];
    
    0 讨论(0)
提交回复
热议问题