[英]Accessing JSON Object property
These are my JSON objects. 这些是我的JSON对象。
({
"0":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F86040788&",
"1":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F87126537&",
"2":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F84915833&",
"3":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F87317484&",
"4":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F86548283&"
})
I fetched them with Ajax and this is how I get to them: 我用Ajax获取它们,这就是我对它们的看法:
data[0]
to data[4]
. data[0]
到data[4]
。
Why is data.1
, etc not working? 为什么
data.1
等不起作用? I don't understand why I can access the objects like this data[0]
, because they are not arrays. 我不明白为什么我可以访问像这个
data[0]
这样的对象,因为它们不是数组。
Why is data.1, etc is not working?
为什么data.1等不起作用?
Thats because data.1
is an invalid syntax according to the grammar of Javascript. 那是因为根据Javascript的语法,
data.1
是无效的语法。 Open your browsers console and try: 打开浏览器控制台并尝试:
var obj = {};
obj[0] = "test";
obj.0; //SyntaxError: Unexpected number
I don't get why I can acess the objects like this data[0], because they are not arrays.
我不明白为什么我可以访问像这个数据[0]这样的对象,因为它们不是数组。
In javascript, arrays and map/dictionary/association array are the same thing. 在javascript中,数组和map / dictionary / association数组是一回事。 You can access by either
object[key]
syntax or object.key
syntax. 您可以通过
object[key]
语法或object.key
语法进行访问。 Only restriction is that it should be parseable by the parser (it should be an identifier), otherwise it would fail -- like the case you have. 唯一的限制是它应该由解析器解析(它应该是一个标识符),否则它会失败 - 就像你拥有的情况一样。 Another example:
另一个例子:
var obj = {"test-data":1, "test": 2};
obj["test"] // 2
obj.test // 2
obj["test-data"]; // 1
obj.test-data //ReferenceError: data is not defined
//^ is a <MINUS> character, parsed as (obj.test - data)
Working with objects: Objects and properties 使用对象:对象和属性
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string.
对象属性名称可以是任何有效的JavaScript字符串,也可以是可以转换为字符串的任何内容,包括空字符串。 However, any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation.
但是,任何不是有效JavaScript标识符的属性名称(例如,具有空格或破折号的属性名称,或以数字开头)只能使用方括号表示法访问。 This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
当要动态确定属性名称时(直到运行时才确定属性名称),此表示法也非常有用。 Examples are as follows:
示例如下:
因为json var name无法从数字开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.