How to access the properties of an object in Javascript

时间:2023-03-09 15:46:17
How to access the properties of an object in Javascript

Javascript has three different kinds of properties: named data property, named accessor property and internal property. There are two kinds of access for named properties: get and put, corresponding to retrieval and assignment, respectively. Please refer to the Ecma-262.pdf.

Here are the ways of accessing named data property.

 var obj = {

     property_1: 123

 };

You can get its value like the following:

 obj.property_1;

Or

obj[“property_1”]; //please note, quote is required here

but you have to use [“xxx”] if you intend to use for/in to access the properties of an object

 for(p in obj)
{
alert(obj[p]);
}

The system will alert undefined if you access like the following within the for/in, the reason is javascript pass the property as string

for (p in obj)
{
alert(obj.p);
}