javascript 元素名称上带有破折号 (-) 字符的 Json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29482226/
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
Json object with dash (-) character on element name
提问by CONvid19
I'm parsing a json
object that contains an element named data-config
.
我正在解析一个json
包含名为data-config
.
ex:
前任:
var video = data.element.data-config;
Whenever I parse this element I'm getting this error:
每当我解析这个元素时,我都会收到这个错误:
ReferenceError: config is not defined
The ReferenceError
doesn't mention data-config
but simply config
.
Any idea why I'm getting this error?
Is this related with the dash (-) character?
在ReferenceError
没有提及data-config
,但根本config
。
知道为什么我会收到此错误吗?这与破折号 (-) 字符有关吗?
回答by Downgoat
Valid Characters
有效字符
In general JavaScript, variable/function names can't contain -
. They can only contain letters, $, and _ (Underscore)
在一般 JavaScript 中,变量/函数名称不能包含-
. 它们只能包含字母、$和_(下划线)
So...
所以...
The error is coming because it's parsing:
错误即将到来,因为它正在解析:
var video
is equal to data.element.data
(valid) minus config
var video
等于data.element.data
(有效)减去config
Solution
解决方案
Because variables can't contain dashes, you need to use what I'm going to call String/Bracket Notation
因为变量不能包含破折号,所以你需要使用我将要调用的字符串/括号表示法
data.element['data-config']
data.element['data-config']
If you need to do more then one, do
如果您需要做更多的事情,请执行
data.element['data-config']['child']
data.element['data-config']['child']
I don't recommend using String/Bracket Notationwhen you don't have to, it's better practice.
我不建议在不必要时使用字符串/括号表示法,这是更好的做法。
回答by charlietfl
You have to use []
notation when object properties contain special characters
[]
当对象属性包含特殊字符时,您必须使用符号
var video = data.element['data-config'];