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

后端 未结 6 1501
渐次进展
渐次进展 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条回答
  •  旧时难觅i
    2020-12-01 08:02

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

    'a' is a string with the value 'a'. a is a variable with the value 'whatever'.

提交回复
热议问题