How do I interpolate a variable as a key in a JavaScript object?

后端 未结 6 1497
渐次进展
渐次进展 2020-12-01 07:22

How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b[\"whatever\"] and have this return 20:

6条回答
  •  佛祖请我去吃肉
    2020-12-01 08:00

    To show all options, I want mention the CoffeeScript way of doing this, which is:

    var a = "whatever";
    var b = (
      obj = {},
      obj["" + a] = 20,
      obj
    );
    
    alert(b.whatever); // 20
    

    Although I prefer:

    var a = "whatever";
    var b = {};
    b[a] = 20;
    
    alert(b.whatever); // 20
    

提交回复
热议问题