javascript 属性名称中是否允许使用破折号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5516106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are dashes allowed in javascript property names?
提问by xecaps12
I was looking at http://docs.jquery.com/Plugins/Authoring#Defaults_and_Optionsto create a simple plugin for jQuery. Following the section about options and settings, I did the following, which didn't work (the script quit when it encountered the setting).
我正在查看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
Once I removed the dash from the background color, things work properly.
从背景颜色中删除破折号后,一切正常。
var settings = {
'location' : 'top',
'backgroundColor': 'blue' // dash removed here
}
...
$this.css('backgroundColor', settings.backgroundColor);
Am I missing something, or are the jQuery docs wrong?
我错过了什么,还是 jQuery 文档错了?
回答by Daniel A. White
no. the parser will interpret it as the subtract operator.
不。解析器将其解释为减法运算符。
you can do settings['background-color']
.
你可以settings['background-color']
。
回答by Rocket Hazmat
Change settings.background-color
to settings['background-color']
.
更改settings.background-color
为settings['background-color']
。
Variables cannot contain -
because that is read as the subtract operator.
变量不能包含,-
因为它被读取为减法运算符。
回答by JaredPar
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.
破折号在 javascript 变量中是不合法的。变量名必须以字母、美元符号或下划线开头,后跟相同或数字。
回答by sdleihssirhc
You can have dashes in strings. If you really wanted to keep that dash, you'd have to refer to the property using brackets and whatnot:
您可以在字符串中使用破折号。如果你真的想保留那个破折号,你必须使用括号和诸如此类的东西来引用属性:
$this.css('backgroundColor', settings['background-color']);
回答by Primoz Rome
You can do something like this:
你可以这样做:
var myObject = {
propertyOne: 'Something',
'property-two': 'Something two'
}
var result1 = myObject.propertyOne
var result2 = myObject['propertyOne']
var result3 = myObject['property-two']