跳轉到內容

JavaScript/物件/練習

來自華夏公益教科書,自由的教科書

主題: 物件

1. 發揮創意。

  • 建立一個物件,描述你的某些身體或心理屬性。
  • 使用 alert 命令顯示該物件。
  • 使用 alert 命令僅顯示該物件中最重要的屬性。
  • 向物件新增另一個屬性。再次顯示完整的物件。
  • 刪除最不重要的屬性。再次顯示完整的物件。
點選檢視答案
"use strict";

// an example

// literal notation
const me = {height:"165 cm", weight: "63 kg", hairColor: "blond"};
alert(JSON.stringify(me));
alert(JSON.stringify(me.height));

me.friendliness = "medium";
alert(JSON.stringify(me));

delete me.hairColor;
alert(JSON.stringify(me));



2. 倉庫裡的商品。

  • 建立兩個物件 shoe_1shoe_2,它們代表鞋子。使用字面量表示法
  • 建立另外兩個物件 shirt_1shirt_2,它們代表襯衫。首先建立空物件。然後向物件新增屬性。
  • 建立一個物件 warehouse,並將所有 4 個物件新增到其中。
  • 顯示倉庫物件中第 4 個商品的價格。
點選檢視答案
"use strict";

// literal notation
const shoe_1 = {category:"shoes", type: "sandals", size: 8, color: "brown"};
const shoe_2 = {category:"shoes", type: "high heels", size: 7, color: "silver", price: "94.50"};

// add properties
const shirt_1 = {};
shirt_1.category = "shirts";
shirt_1.size = "XL";
shirt_1["color"] = "blue";
shirt_1["material"] = "cotton";
alert(JSON.stringify(shirt_1));

// mixture
const shirt_2 = {size: "S", color: "green" };
shirt_2.category = "shirts";
shirt_2.price = 19.99;
alert(JSON.stringify(shirt_2));

const warehouse = {prod_1: {...shoe_1}, prod_2: {...shoe_2}, prod_3: {...shirt_1}, prod_4: {...shirt_2} };
alert(JSON.stringify(warehouse));

// the price of the 4.-th product
alert(JSON.stringify(warehouse.prod_4.price));

這個例子不是非常優雅,但展示了不同的技術。在生產環境中,你可能會使用迴圈和陣列。

華夏公益教科書