Meaning of variable in array as property name?

前端 未结 3 649
醉梦人生
醉梦人生 2021-01-29 12:00
var expertise = \'journalism\'
var person = {
    name: \'Sharon\',
    age: 27,
    [expertise]: {
        years: 5,
        interests: [\'international\', \'politics\'         


        
相关标签:
3条回答
  • 2021-01-29 12:30

    It is syntactic sugar, introduced in ECMAScript 6

    Computed property names

    Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already.

    ECMAScript 5

    var expertise = 'journalism'
    var person = {
        name: 'Sharon',
        age: 27
    }
    person[expertise] = {
        years: 5,
        interests: ['international', 'politics', 'internet']
    }
    

    ECMAScript 6

    var expertise = 'journalism'
    var person = {
        name: 'Sharon',
        age: 27,
        [expertise]: {
            years: 5,
            interests: ['international', 'politics', 'internet']
        }
    }
    
    0 讨论(0)
  • 2021-01-29 12:51

    So that, you can refer to the string value stored in the expertise variable, that is, journalism.

    var expertise = 'journalism'
    var person = {
    name: 'Sharon',
    age: 27,
    [expertise]: {
    years: 5,
    interests: ['international', 'politics', 'internet']
    }
    }
    
    console.log(person.journalism.years);
    console.log(person[expertise].years);

    Run this code snippet, and note the two console logs.

    Without the brackets, you'd have the string "expertise" instead, as the property name.

    You can read more about it here on MDN.

    Computed property names

    Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already. Now you can use the same syntax in object literals, too

    var param = 'size';
    var config = {
      [param]: 12,
      ['mobile' + param.charAt(0).toUpperCase() + param.slice(1)]: 4
    };
    
    console.log(config); // {size: 12, mobileSize: 4}
    
    0 讨论(0)
  • 2021-01-29 12:54

    It is Computed property (ES2015) :

    This is a sample:

    var prop = 'foo';
    var o = {
      [prop]: 'hey',
      ['b' + 'ar']: 'there'
    };
    

    and you may use :

    console.log(o.foo)  // hey
    console.log(o.bar)  // there
    
    0 讨论(0)
提交回复
热议问题