跳轉到內容

JavaScript/物件

來自華夏公益教科書,開放的書籍,開放的世界



在 JavaScript 中,一個物件屬性的集合;屬性是鍵值對。鍵是字串或符號。值可以是任何資料型別 - 包括函式(在這種情況下,它們被稱為方法)。

物件看起來像關聯陣列,以雜湊表的形式實現。但在實踐中,JavaScript 引擎可能以其他方式實現它們以實現最佳效能。

請注意,JavaScript 物件與 JSON 不完全相同。JSON 是一種用於物件文字表示(“序列化”/“反序列化”)的格式,也可以在其他語言或純文字編輯器中完成。

建立物件

[編輯 | 編輯原始碼]

JavaScript 語法支援不同的方法來建立物件。

'字面量表示法' 使用大括號 { }

"use strict";

// an empty object (no properties)
const obj_0 = {};
alert(JSON.stringify(obj_0));

// 'obj_1' contains a set of 3 properties. The value of key 'c' is
//         a second object with an empty set of properties.
const obj_1 = { a: "Any string", b: 42, c: {} };
alert(JSON.stringify(obj_1));

// using variables
const a = "Any string";
const b = 42;
const c = {};
const obj_2 = { a: a, b: b, c: c };
alert(JSON.stringify(obj_2));

// shorthand usage of variables
const obj_3 = { a, b, c };
alert(JSON.stringify(obj_3));

建構函式
new Object() 建構函式建立一個新物件。

"use strict";
const obj_4 = new Object({ a: 5, b: 42 });
alert(JSON.stringify(obj_4));

Object.create()
Object.create() 方法從現有物件建立一個新物件。

"use strict";
const obj_5 = Object.create({ a: 5, b: 42 });
alert(JSON.stringify(obj_5));  // ???
alert(JSON.stringify(obj_5.a));
console.log (obj_5);

讀取屬性

[編輯 | 編輯原始碼]

每個屬性都包含一個鍵值對。要讀取屬性的值,可以使用兩種語法方式中的任何一種,即點表示法方括號表示法

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };

// dot notation
alert(person.firstName);   // no " " or ' '

// bracket notation
alert(person["firstName"]); // must use a string

// bracket notation using a variable
const fn = "firstName";
alert(person[fn]);

如果您不知道鍵怎麼辦?要獲取所有現有鍵的列表,請使用Object.keys() 方法。它返回一個數組,其元素是字串。這些字串可以在迴圈中使用以訪問值。由於在許多情況下需要這樣的迴圈,JavaScript 為這種情況提供了一個特殊的語言元素。for .. in 迴圈選擇鍵並迴圈遍歷所有屬性。

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };
alert(Object.keys(person));   // firstName, lastName

// The for .. in loop selects all existing keys and loops over the properties
for (const k in person) {
  alert('The key is: ' + k + '. The value is: ' + person[k]);
}

類似於Object.keys() 方法,還有兩種方法Object.values()Object.entries() 用於分別獲取值和屬性(鍵和值)。在後一種情況下,您將獲得一個數組陣列(每個陣列有兩個元素)。

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };
alert(Object.values(person));   // Albert, Einstein

// for .. of loops differ from for .. in loops in syntax AND semantic; see chapter 'Loops'
for (const [k, v] of Object.entries(person)) {
  alert('The key is: ' + k + '. The value is: ' + v);
}

新增或修改屬性

[編輯 | 編輯原始碼]

您可以使用點表示法方括號表示法來新增或修改屬性。上面讀取操作和寫入操作的語法之間沒有區別。

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };

// add properties
person.bornIn = "Ulm";
person["profession"] = "Physicist";
alert(JSON.stringify(person));

// modify properties
person.bornIn = "Germany";
person["profession"] = "Theoretical Physics";
alert(JSON.stringify(person));

在上面的示例中,變數“person”是用關鍵字const 建立的。因此無法為它分配新值,但可以操作其屬性。在操作屬性時,原始物件保持不變。

刪除屬性

[編輯 | 編輯原始碼]

delete 運算子從物件中刪除整個屬性 - 包括鍵和值。這與將nullundefined 儲存在值中的情況不同。

同樣,您可以使用點表示法方括號表示法

"use strict";
const person = {firstName: "Albert", lastName: "Einstein", bornIn: "Ulm", profession: "Physicist" };

delete person.bornIn;
delete person["profession"];
alert(JSON.stringify(person));

合併物件

[編輯 | 編輯原始碼]

JavaScript 提供了“擴充套件語法”(三個點)。它將物件擴充套件為其屬性(鍵值對)或將陣列擴充套件為其元素。當您想要將多個物件合併為單個物件時,這可能很有用。

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };
const address = {city: "Ulm" };

// expand the two objects (and merge them)
const newPerson = {...person, ...address};
alert(JSON.stringify(newPerson));
// The result is an object with 3 properties. All values are strings.
// {firstName: "Albert", lastName: "Einstein",city: "Ulm"}

// which is different from the version without the 'spread syntax':
const newPerson1 = {person, address};
alert(JSON.stringify(newPerson1));
// The result is an object with 2 properties. Both values are objects.
// {person: {firstName: "Albert", lastName: "Einstein"}, address: {city: "Ulm"}}

函式/方法作為物件的一部分

[編輯 | 編輯原始碼]

屬性的值部分可能包含一個函式體;參見此處。在這種情況下,該函式稱為方法

"use strict";

// only definitions here, no execution!
const city = {
  showName: function (cityName) {
              if (typeof cityName === "undefined") {
                alert("Sorry, I don't know my name.");
              } else {
                alert("The name of the city is: " + cityName);
              }
            },

  // this works too!
  showPopulation(count) {
    alert(count + " Inhabitants");
  },
};

// JSON's 'stringify()' doesn't support the serialization of methods. Use 'console.log()' instead.
console.log(city);

// executions
city.showName();
city.showName("Nairobi");
city.showPopulation(4500000);
...可在另一個頁面上找到(點選此處)。
華夏公益教科書