Computable property names for JavaScript objects

Table of contents

Application Scenario

In JavaScript, you can access object properties by combining dots (.) or square brackets ([]) with property names, but if the property name contains special or Chinese , or needs to be calculated to get the property name, then use the method Combination of parentheses and calculations get.

example

let obj = {
    
    };
let a = "a";
obj['b B'] = "Bb"; // 属性名中有空格 
obj[a + ' A'] = "Aa"; // 属性名由表达式计算得到
console.log(obj);// {b B: "Bb", a A: "Aa"}

Using Computable Property Names as Properties and Values ​​in Literal Objects

let a = "a";
let obj = {
    
    
    ['b B'] : "Bb",
    [a + ' A'] : "Aa"
};
console.log(obj)
//{b B: "Bb", a A: "Aa"}

Guess you like

Origin blog.csdn.net/Mr_Bobcp/article/details/126086975