简体   繁体   中英

Use a property name stored in a var, dot and bracket notation

I'm on the bracket and dot notation challenge in JS, I understand (more or less) how it works, but I can't with a little point:

Why I can't use Dot Notation whwn a property name is stored in a variable?

This is undefined:

var car = {
seats: "cloth",
engine: "V-6"
};
var s = "seats";
function show_seat_type(sts) {
window.alert(car.sts); // undefined
}
show_seat_type(s);

This is OK

var car = {
seats: "cloth",
engine: "V-6"
};
var s = "seats";
function show_seat_type(sts) {
window.alert(car[sts]); // works
}
show_seat_type(s);

But why? Thanks guys.

By using dot notation, you indicate to the interpreter that there is a property of car that you know is named "sts". It doesn't attempt to resolve it. If you were to have an object

var car = {
seats: "cloth",
sts : "foo",
engine: "V-6"
};

Your dot notation code would work, but return the string "foo".

Alternatively, by using the bracketed notation the interpreter expects a string, so any variable it receives will be resolved to a string. Now that you know that, consider this. How would you expect either of these calls to behave?

car."sts"
car["sts"]

The first call errors out, and the second one returns "foo". Hopefully this illustrates the differences between these two methods of variable reference.

Dot notation is to be preferred , and JS linters warn about the use of bracket notation.

The use of the bracket notation should be reserved for dynamic property names, just like in your (second) example.

To answer to your question:

car.sts is the same as car["sts"]

So

car[sts] is the same as cat.<the value of sts> :

var sts = "seats";
car[sts]; // equal to car.seats

With the dot notation , the property name must be a valid identifier , whereas with the brack notation , it could be any string, even the empty string '' ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM