在Javascript中,對象和數組是兩種基本的資料類型,而且它們也是最重要的兩種資料類型。
對象是已命名的值的一個集合,而數組是一種特殊對象,它就像數值的一組有序集合。
4.1 關聯陣列的對象 Objects as Associative Arrays
對於對象,其屬性相當於已命名的字串值的一個集合。可以使用數組存取運算子[]來提取屬性。
對象可以使用"."來存取一個對象屬性,而數組更常用的存取屬性運算子是[].下面兩個運算式等效:
1object.property
2object["property"]
以上兩種方式的重要區別是:前者的屬性名稱是標識符,後者的屬性名稱卻是一個字串。★
以下原文說明了它的重要性:
In C, C++, Java, and similar strongly typed languages, an object can have only a fixed number of properties, and the names of these properties must be defined in advance. Since JavaScript is a loosely typed language, this rule does not apply: a program can create any number of properties in any object. When you use the . operator to access a property of an object, however, the name of the property is expressed as an identifier. Identifiers must be typed literally into your JavaScript program; they are not a datatype, so they cannot be manipulated by the program
On the other hand, when you access a property of an object with the [] array notation, the name of the property is expressed as a string. Strings are JavaScript datatypes, so they can be manipulated and created while a program is running. So, for example, you can write the following code in JavaScript:
1var addr = "";
2for(i = 0; i < 4; i++) {
3 addr += customer["address" + i] + '\n';
4}
4.2 通用的object屬性和方法
① constructor屬性
引用該屬性初始化對象的構造。
② toString()方法
把對象轉換成字串時,就會調用這個方法
③ toLocalString()方法
返回一個本地化字串表示
④ valueOf()方法
與toString()方法很像,它是當Javascript把一個對象轉換為某種基礎資料型別 (Elementary Data Type),即數字而非字串時,調用的方法
預設的valueOf並不做什麼有意義的事情。
⑤ hasOwnProperty()方法
The hasOwnProperty() method returns true if the object locally defines a noninherited property with the name specified by the single string argument. Otherwise, it returns false. For example:
1var o = {};
2o.hasOwnProperty("undef"); // false: the property is not defined
3o.hasOwnProperty("toString"); // false: toString is an inherited property
4Math.hasOwnProperty("cos"); // true: the Math object has a cos property
也即是說,如果參數中指定的字串,相當於對象的一個屬性,該屬性在本類中實現,返回true,在繼承類中實現,返回false.
⑥ propertyIsEnumerable() 方法
如果字串參數所指定的名字,相當於對象的一個非繼承的屬性;且屬性可以在一個for/in迴圈中枚舉。返回true.
1var o = { x:1 };
2o.propertyIsEnumerable("x"); // true: property exists and is enumerable
3o.propertyIsEnumerable("y"); // false: property doesn't exist
Note that all user-defined properties of an object are enumerable.(一個對象的所有使用者定義的屬性都是可以枚舉的。) Nonenumerable properties are typically inherited properties (see Chapter 9 for a discussion of property inheritance), so this method almost always returns the same result as hasOwnProperty().
⑦ isPrototypeOf()方法
The isPrototypeOf() method returns true if the object to which the method is attached is the prototype object of the argument. Otherwise, it returns false. For example:
1var o = {}
2Object.prototype.isPrototypeOf(o); // true: o.constructor == Object
3Object.isPrototypeOf(o); // false
4o.isPrototypeOf(Object.prototype); // false
5Function.prototype.isPrototypeOf(Object); // true: Object.constructor==Function