2017-03-17 48 views
1

我已经在这个格式的值:靶向对象的数组在JavaScript

var state = [{"industry-type":"football","your-role":"coach"}] 

我想输出“足球”。我怎样才能做到这一点?

我试过state[0].industry-type但它返回一个错误:

Uncaught ReferenceError: type is not defined 

任何帮助表示赞赏。

+0

你有什么是对象的数组(S ),而不是JSON。 –

回答

2

它不喜欢的“ - ”你的财产名称,请尝试:

state[0]['industry-type'] 
1

这是因为你不能-直接访问属性。

var state = [{"industry-type":"football","your-role":"coach"}]; 
 

 
console.log(state[0]['industry-type']);

1

-符号在Javascript中保留的,你不能用它来指代一个对象的属性JavaScript,因此认为你试图做减法:state[0].industry - type;因此错误“未捕获的ReferenceError :type is not defined“ - 它正在寻找一个名为type的变量来减去,它找不到。

相反,是指它由:

state[0]['industry-type'] 

因为在Javascript,object.propertyobject['property']是相等的。


对于它的价值,如果你有过这些名字控制,在Javascript中的最佳实践与Camel Case命名的东西,所以你的变量将被定义为:然后

var state = [{"industryType":"football","yourRole":"coach"}] 

,你可以像访问:

state[0].industryType 
1

为了能够使用点符号那么你:

...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问题:

What characters are valid for JavaScript variable names?

0

你需要使用括号标记的属性 -

state[0]['industry-type']