在 javascript 属性名中允许破折号吗?

我在看 http://docs.jquery.com/Plugins/Authoring#Defaults_and_Options为 jQuery 创建一个简单的插件。在关于选项和设置的部分之后,我做了以下工作,但是没有起作用(脚本遇到设置时退出)。

var settings = {
'location' : 'top',
'background-color': 'blue'
}
...
$this.css('backgroundColor', settings.background-color); // fails here

一旦我从背景颜色中移除破折号,事情就能正常工作了。

var settings = {
'location' : 'top',
'backgroundColor': 'blue' // dash removed here
}
...
$this.css('backgroundColor', settings.backgroundColor);

Am I missing something, or are the jQuery docs wrong?

88544 次浏览

不,解析器会将其解释为减法运算符。

你可以做 settings['background-color']

settings.background-color改为 settings['background-color']

变量不能包含 -,因为它是作为减法运算符读取的。

你可以用字符串表示破折号。如果你真的想保留这个破折号,你必须使用括号和其他东西来引用这个属性:

$this.css('backgroundColor', settings['background-color']);

Dashes are not legal in javascript variables. A variable name must start with a letter, dollar sign or underscore and can be followed by the same or a number.

You can do something like this:

var myObject = {
propertyOne: 'Something',
'property-two': 'Something two'
}


for (const val of [
myObject.propertyOne,
myObject['propertyOne'],
myObject['property-two']
]){
console.log(val)
}