简体   繁体   中英

What do square brackets around a property name in an object literal mean?

I've been writing in JS for a while and have not used this form:

  dist: {
    files: {
      [bpr + 'lib/Monster.min.js']: ['<%= concat.dist.dest %>']
    }
  }
}

the

[]:[]

it works, I just have not used it or seen it before.

Only recently with ES6. They are called "computed property names"

From MDN :

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.

In ES6 square bracket is part of os the object literal when using computed key pairs.

For example:-

Problem Below the string "key" times 5 makes a computed key named "key"*5, now without using square brackets this result in a syntax error

const newObject = {
    "key"*5:"value"
}

The Solution The solution will be to use a square bracket before using a computed property as a key

const newObject = {
    ["key"*5]:"value"
}

For more reference of how to create objects check out this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM