我已经在这个格式的值:靶向对象的数组在JavaScript
var state = [{"industry-type":"football","your-role":"coach"}]
我想输出“足球”。我怎样才能做到这一点?
我试过state[0].industry-type
但它返回一个错误:
Uncaught ReferenceError: type is not defined
任何帮助表示赞赏。
我已经在这个格式的值:靶向对象的数组在JavaScript
var state = [{"industry-type":"football","your-role":"coach"}]
我想输出“足球”。我怎样才能做到这一点?
我试过state[0].industry-type
但它返回一个错误:
Uncaught ReferenceError: type is not defined
任何帮助表示赞赏。
它不喜欢的“ - ”你的财产名称,请尝试:
state[0]['industry-type']
这是因为你不能-
直接访问属性。
var state = [{"industry-type":"football","your-role":"coach"}];
console.log(state[0]['industry-type']);
的-
符号在Javascript中保留的,你不能用它来指代一个对象的属性JavaScript,因此认为你试图做减法:state[0].industry - type;
因此错误“未捕获的ReferenceError :type is not defined“ - 它正在寻找一个名为type
的变量来减去,它找不到。
相反,是指它由:
state[0]['industry-type']
因为在Javascript,object.property
和object['property']
是相等的。
对于它的价值,如果你有过这些名字控制,在Javascript中的最佳实践与Camel Case命名的东西,所以你的变量将被定义为:然后
var state = [{"industryType":"football","yourRole":"coach"}]
,你可以像访问:
state[0].industryType
为了能够使用点符号那么你:
...property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number.
从MDN
像其他的答案中指出,你必须用方括号来访问对象是不是有效的JavaScript标识的属性名称。
例如
state[0]["industry-type"]
相关SO问题:
你需要使用括号标记的属性 -
state[0]['industry-type']
你有什么是对象的数组(S ),而不是JSON。 –