And finally, let's go over retrieving property values. Throughout this section, we've been using dot notation to get the value of an object's property:
someObj.propName;
However, remember that we can also use bracket notation:
someObj["propName"];
An advantage of bracket notation is that we are not restricted to just using strings in the brackets. We can also use variables whose values are property names:
varsomeObj = {propName: someValue};varmyProperty ="propName";
someObj[myProperty];
The last line is exactly the sameas using someObj["propName"];
.
Sample Codes:
var james = {
job: "programmer",
married: false
};
// set to the first property name of "james"
var aProperty = "job";
//var aProperty = james.job;
// print the value of the first property of "james"
// using the variable "aProperty"
//console.log(aProperty);
console.log(james.married);
console.log(james.job);
console.log(james["job"]);
console.log(james[aProperty]);
++++++++++++++++++++++++
result:
falseprogrammerprogrammerprogrammer