Javascript Property Access Using Brackets
Solution 1:
When you use brackets, the expression inside the brackets is evaluated. What's the value of the expression
a
?? Well, if "a" isn't a declared variable, it's nonsense. When you use .
notation, the identifier (and it must be an identifier) following the operator is treated as a string. It's just the way the language works.
Solution 2:
The reason you're getting a ReferenceError
for object[a]
is because a literal a
is a variable in javascript. "a"
is a string containing the letter a.
You can use the dot notation object.a
or the bracket notation with object["a"]
object.a; //=> 0object["a"]; //=> 0object[1]; //=> 1object["1"]; //=> 1
Or you can use a variable for access
var x = "a";
object[x]; //=> 0var y = 1;
object[y]; //=> 1
Solution 3:
You are correct.
a
there is a token which the engine assumes is a variable.
If you type "a"
JS knows it's a string-primitive.
If you type 0
, JS knows it's a number-primitive.
So on top of obj.a
, obj["a"]
, obj[0]
, obj["0"]
, you can also say:
var a = 0;
obj[a]; // 0
Your app is exploding, because a
hasn't been defined yet, and now you want to use it.
And yes, this is the expected behaviour. What's inside of the brackets isn't seen as a "part" of the object -- it's a way of saying "give me the value of the object which is referenced by this key", where the key might be a number or string (or something that can be coerced into a string or number).
In the future, with maps and weakmaps, you would actually be able to use other objects/functions as keys as well.
var obj = newMap(),
func = function () { },
el = document.getElementById("myId");
obj[func] = 1;
obj[el] = 2;
Right now, these things technically work... ...but only because they're converted to their string values... ...so if you had two functions which were written the same (but technically two different objects), you would overwrite values, currently. Inside of a map, they'd be treated as separate objects.
Using DOM elements is even worse, right now, as it might be useful to store hundreds of those and bind references to them, so that you don't have to keep looking for them... ...but for now, you need to make a unique ID number/key for each one, and store that, and remember the keys, and then create a child object to hold the data you want...
Whereas in the future, with maps, you could say:
var my_els = document.querySelector(".lots-of-els");
for (let el of my_els /* also the future */) {
console.log( my_map_of_data[el].info );
}
Post a Comment for "Javascript Property Access Using Brackets"