六角學院 JS 核心筆記 (十八)【運算子、型別與文法】- 物件結構、取值、新增、刪除

前言

JavaScript 的兩大型別:原始型別 (Primitive type) 及參考型別 (Reference type) 中,參考型別就是 Object 型別。Object {}Array []Function () 都是物件型別。

先來認識我們一般認知上由 {} 組成的物件。

建立物件

物件實字 Object literals

直接由 {}、屬性 (Property) 和值 (Value) 的結構建立出來的物件。

1
2
3
4
5
6
7
8
9
10
11
let family = {
name: "Jenifer", // property: value
age: 10,
members : {
mom: "Mary",
dad: "David"
},
callFamily: function() {
console.log("We are Potter family.");
}
}

物件的建構式 Constructor functions

使用 new Object() 來建立物件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 傳入一個物件
let family2 = new Object(family); // family2 === family returns true

// 使用 dot notation
let family3 = new Object();
family3.name = "Jenifer";
family3.age = 10;
// ...

// 使用 bracket notation
let family4 = new Object();
family4["name"] = "Jenifer";
family4["age"] = 10;
// ...

注意:如果使用 new Object(1) 傳入數字,會產生 Number 包裹物件 Number {1},如果傳入字串 new Object("hi") 會產生 String 包裹物件 String {"hi"}

物件取值

注意:所有的屬性 (Property) 都是字串,數字也會自動轉換成字串。如下 1234 不用加引號就會轉成字串,"@#$" 則必需加引號,否則出現 Uncaught SyntaxError: Invalid or unexpected token

1
2
3
4
5
6
7
8
9
10
11
12
13
let obj = {
name: "Jenifer", // property: value
age: 10,
members : {
mom: "Mary",
dad: "David"
},
1234 : "Property is a string.",
"@#$" : "Weird symbol.",
callFamily: function() {
console.log("We are Potter family.");
}
}

dot notation 取值

1
2
3
4
5
console.log(obj.name);         // Jenifer
console.log(obj.members.mom); // Mary
console.log(obj.1234); // Uncaught SyntaxError: missing ) after argument list
console.log(obj.@#$); // Uncaught SyntaxError: Invalid or unexpected token
console.log(obj.callFamily()); // We are Potter family.

bracket notation 取值

1
2
3
4
5
console.log(obj["name"]);           // Jenifer
console.log(obj["members"]["mom"]); // Mary
console.log(obj["1234"]); // Property is a string.
console.log(obj["@#$"]); // Weird symbol.
console.log(obj["callFamily"]()); // We are Potter family.

物件新增

dot notation 賦值

1
obj.dog = "Lucky";

bracket notation 賦值

1
obj["cat"] = "Butter";

物件刪除

dot notation 刪除

1
delete obj.dog

bracket notation 賦值

1
delete obj["@#$"]

補充:delete

全域的環境下,如下 a 是變數 b 是屬性。

The JavaScript delete operator removes a property from an object.

a 不是屬性不能被刪除。b 可以被刪除

1
2
3
4
5
var a = 10; // 為 window 物件增加一個「變數」
b = 3; // 為 window 物件增加一個「屬性」

delete a; // return false
delete b; // return true

參考資料:
六角學院:JavaScript 核心篇 - 邁向達人之路