我看到我的应用程序中的一些代码具有以下创建对象的方式,
let request = {
'name' : this.form.value.name
};
我更喜欢不带引号的属性名称,例如,
let request = {
name : this.form.value.name
}
哪个是正确的,有什么区别吗?
最佳答案
除非对象键是数字文字或有效的标识符名称,否则您需要将其引用以避免抛出语法错误。换句话说,如果属性名称是数字文字或有效的标识符名称,则只能省略引号。当然,如果属性名是一个字符串字面量,它已经被定义引用了。
var object = {
// `abc` is a valid identifier; no quotes are needed
abc: 1,
// `123` is a numeric literal; no quotes are needed
123: 2,
// `012` is an octal literal with value `10` and thus isn’t allowed in strict mode; but if you insist on using it, quotes aren’t needed
012: 3,
// `π` is a valid identifier; no quotes are needed
π: Math.PI,
// `var` is a valid identifier name (although it’s a reserved word); no quotes are needed
var: 4,
// `foo bar` is not a valid identifier name; quotes are required
'foo bar': 5,
// `foo-bar` is not a valid identifier name; quotes are required
'foo-bar': 6,
// the empty string is not a valid identifier name; quotes are required
'': 7 };
有关更多引用,请参阅 here
关于Javascript - 在引号和直接写属性名称有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52732583/