Meaning of variable in array as property name?

前端 未结 3 651
醉梦人生
醉梦人生 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']
        }
    }
    

提交回复
热议问题