Using Square Brackets in Object Literal Keys
It may be difficult to understand how keys can be assigned using square brackets within an object literal. Let's dive into the explanation behind this ES2015 syntax.
The code snippet you provided:
let a = "b"
let c = {[a]: "d"}
uses the computed property name syntax, which is a shorthand for the traditional ES3/5 someObject[someKey] assignment. In other words, it expands to:
var a = "b"
var c = {}
c[a] = "d"
This syntax allows you to dynamically generate property names based on variables or expressions, providing greater flexibility in object construction. When using this feature, ensure that the property name is enclosed in square brackets, as in [a] in the example.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3