7.2 对象的属性(Object Properties )

可以通过 . 操作符来存取对象的属性值。 . 操作符左边的值必须为对象,通常它会是包含对象引用的一个变量的名字,也可以是任何返回一个对象的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();

 

  Deleting Properties

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.


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值