im having trouble understanding syntax of object literals in javascript when considering following code sample (from mozilla’s developer site):
var car = { manycars: {a: "saab", "b": "jeep"}, 7: "mazda" }; console.log(car.manycars.b); // jeep console.log(car[7]); // mazda
my current understanding of javascript object literals this: if give key, value pair , key of data type, works python dictionary, making car[key] return value set key. if give key text, defines variable in 'car' set value associated key. however, in above, "b"
string, car.manycars.b
can called if variable set "jeep"
, , car.manycars["b"]
valid syntax, returning "jeep"
.
i wondering if give me clear explanation of happens when declare object literal, because current understanding not complete.
in javascript, keys in object literal notation treated strings whether or not in quotes. thus, this:
var car = { manycars : {a: "saab", "b": "jeep"}, 7: "mazda" };
if this:
for (var k in car) { console.log("key: " + k + " (type: " + typeof(k) + ")"); }
the output be:
key: 7 (type: string)
key: manycars (type: string)
note (apparently) numeric key 7
string
. can use javascript keywords keys in object literal.
note when accessing value key, rules more stringent. instance, must use subscript notation , quotes when key reserved word. also, bare key in object literal must (if isn't numeric literal) valid javascript identifier name, cannot contain spaces, commas, or javascript operators (+
, =
, etc.).
Comments
Post a Comment