可能重复:
What is the difference between object keys with quotes and without quotes?
我大多数人都知道使用它的JavaScript,但有些东西我还不明白。
这两个对象文字有什么区别:
var obj1 = {
myProp: '123'
};
var obj2 = {
'myProp': '123'
};
它们只是“同义词”,还是存在细微差别?
谢谢!
答案 0 :(得分:3)
在对象初始值设定项语法中,键可以是数字文字,标识符或字符串。
var obj1 = {
1e9: "123" //valid because it's a numeric literal
}
var obj2 = {
$_ASd: "123" //Valid because it's a valid identifier I.E. you could make a variable called $_Asd
}
var obj3 = {
$ hello world: "123" //invalid because it's not an identifier, I.E. you could not make a variable called $ hello world
}
var obj4 = {
'$ hello world': "123" //valid because it's a valid string
}
之后,无论语法是什么,密钥都会转换为字符串,因此在1e9
的情况下,密钥将是字符串"1000000000"
。
答案 1 :(得分:1)
当内部没有操作员时没有。
var obj1 = {
my+Prop: '123' // illegal
};
var obj2 = {
'my+Prop': '123' // legal
};