可以通过 . 操作符来存取对象的属性值。 . 操作符左边的值必须为对象,通常它会是包含对象引用的一个变量的名字,也可以是任何返回一个对象的javascript 的表达式。 . 操作符右边的值必须为一个标识符,不能是字符串或一个表达式。
Object properties work like variables: you can store values in them and read values from them.
(对象的属性类似于变量的工作方式,)
var book = {};
// Set a property in the object.
book.title = "JavaScript: The Definitive Guide"
// Set some more properties. Note the nested objects.
book.chapter1 = new Object();
book.chapter1.title = "Introduction to JavaScript";
book.chapter1.pages = 11;
book.chapter2 = { title: "Lexical Structure", pages: 6 };
// Read some property values from the object.
alert("Outline: " + book.title + "\n\t" +
"Chapter 1 " + book.chapter1.title + "\n\t" +
"Chapter 2 " + book.chapter2.title);
属性的枚举
可以用 for/in 来遍历、枚举对象的所有属性
举例:
function DisplayPropertyNames(obj) {
var names = "";
for(var name in obj) names += name + "\n";
alert(names);
}
Note:for/in 循环列出的属性没有特定顺序,能列举出所有的用户定义的属性,但不能列举出某些预定义的属性或方法。
检查属性是否存在(Checking Property Existence)
可以用 in 操作符检测属性是否存在。
The left side of this operator should be the name of the property as a string. The right side should be the object to be tested
if ("x" in o) o.x = 1;
if you query a property that does not exist, the undefined value is returned
if (o.x !== undefined) o.x = 1;
Note that it is possible for a property to exist but still be undefined. For example, if you write:
o.x = undefined;
Note also that the !== operator was used earlier instead of the more common != operator. !== and === distinguish between undefined and null
// If the doSomething property exists and is not null or undefined,
// then assume it is a function and invoke it!
if (o.doSomething) o.doSomething();
You can use the delete operator to delete a property of an object:
delete book.chapter2;
Note that deleting a property does not merely set the property to undefined; it actually removes the property from the object. After deletion, for/in will not enumerate the property and the in operator will not detect it.