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

后端 未结 6 1500
渐次进展
渐次进展 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

    This works in Firefox 39 and Chrome 44. Don't know about other browsers. Also it doesn't work in nodejs v0.12.7.

    var a = "whatever";
    var b = { [a]: 20 };
    console.log(b["whatever"]); // shows 20
    

    That is, to interpolate a variable, enclose it in brackets.

    I'm not sure if this is a part of any standard. Originally, I saw such syntax here: https://hacks.mozilla.org/2015/07/es6-in-depth-classes/ where the author defined:

    [functionThatReturnsPropertyName()] (args) { ... }
    

    I'm also not sure if you should use that syntax. It's not widely known. Other members on your team might not understand the code.

提交回复
热议问题