These are my JSON objects.
({
"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:
data[0]
to data[4]
.
Why is data.1
, etc not working? I don't understand why I can access the objects like this data[0]
, because they are not arrays.
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. 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. 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:
because json var name could not start from digit
Why is data.1, etc is not working?
Thats because data.1
is an invalid syntax according to the grammar of Javascript. 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.
In javascript, arrays and map/dictionary/association array are the same thing. You can access by either object[key]
syntax or object.key
syntax. 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)