[英]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:用JS写了一段时间,没用过这种形式:
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.直到最近才使用 ES6。 They are called "computed property names"
它们被称为“计算属性名称”
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names.
从 ECMAScript 2015 开始,对象初始值设定项语法也支持计算属性名称。 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.在 ES6 中,方括号是使用计算密钥对时对象字面量的一部分。
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问题在字符串“key”乘以 5 下方生成一个名为“key”*5 的计算键,现在不使用方括号这会导致语法错误
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有关如何创建对象的更多参考,请查看此链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.