物件基礎

Vicky
宅宅薇琪 [前端學習筆記]
5 min readFeb 23, 2021

寫程式很常使用 “物件” 的方式去撰寫。物件好比描述房子裡面的設施種類內容,如有游泳池、有陽台、有幾樓等,這些都可稱為物件資訊。物件是用來描述一個東西內細部的資訊。

物件格式架構

  1. 物件的開頭是使用大括號
  2. 物件內每筆資料都要使用「逗號」隔開,最後一筆資料可以不用加上「逗號」
  3. 屬性對應的值即 value

很多資料可以統一記錄在物件裡,物件格式如下

let 物件名稱 {
屬性 : 值,
屬性 : 值
}

假設原本使用變數描述一個家庭

let motherName = "Mary";
let fatherName = "Tom";
let dogs = 3;

若改成物件格式結構撰寫如下

let home = {           // 等同宣告一個變數 home,裡面放物件資料
motherName: "Mary", // string
fatherName: "Tom", // string
dogs: 3, // number
isWakeUp: false // 布林值
};

檢查一下物件格式是否正確

console.log(home); 
// {motherName: "Mary", fatherName: "Tom", dogs: 3, isWakeUp: false}

如何讀取物件的值

方法一 : 使用「點」來尋找物件裡的屬性

「點」後面只能接字串,不能接數字開頭的屬性,會跳錯。

let motherName = "Mary";
let fatherName = "Tom";
let dogs = 3;

let home = {
motherName: "Mary",
fatherName: "Tom",
dogs: 3,
isWakeUp: false
};
console.log(home); // 選取整個物件資料
console.log(home.dogs); // 3 (選取 home 這個物件裡的屬性 dogs)

取出屬性值並賦予在新的變數上 (取出屬性值 3 賦予到新的記憶體位置上)

let tomDogs = home.dogs;  
console.log(tomDogs); // 3

方法二 : 使用「中括號」的方式讀取屬性並取值

物件名稱 ['屬性']    // 屬性頭尾要使用「單引號」包起來
  1. 屬性視同字串
  2. 屬性頭尾要使用「單引號」 包起來
  3. 若屬性名稱為數字可以不用引號包住,直接取值即可
  4. 也可使用變數的方式來取值
let home = {
motherName: "Mary",
fatherName: "Tom",
dogs: 3,
isWakeUp: false
};
console.log(home['fatherName']); // Tom

讀取 home 物件,「中括號」內帶的是變數 a,變數 a 讀取記憶體空間的位置(值為 ‘motherName’)

let a = 'motherName';
console.log(home[a]); // Mary

✏️ 補充 : 物件讀取資料判斷時間

當今天遇到奇怪格式無法讀取時,可以使用「中括號」字串取值的方式

let home = {
motherName: "Mary",
fatherName: "Tom",
"001" : "hello",
2 : "我是 2",
};
// console.log(home.2); // 跳錯,「點」後面無法使用開頭為數字的屬性來選取值
console.log(home['001']); // hello
console.log(home[001]); // undefined
console.log(home[2]); // 我是 2 (若屬性名稱為數字可以不用引號包住)
console.log(home['2']); // 我是 2

新增物件屬性

試著新增一組資料到物件 home 裡

  1. 先新增一組空物件
  2. 把資料一筆一筆新增至物件裡
let home = {};
home.motherName = "Mary";
home.dogs = 3;
home.isWakeUp = false;
console.log(home); // {motherName: "Mary", dogs: 3, isWakeUp: false}

修改物件值 (修改原本的物件屬性值)

let home = {
motherName: "Mary",
fatherName: "Tom",
dogs: 3,
isWakeUp: false
};
home.motherName = "Jane"; // 修改原本的物件屬性值

也可取屬性值直接做計算

home.dogs = home.dogs + 1;
home.dogs += 1;
console.log(home);
// {motherName: "Jane", fatherName: "Tom", dogs: 5, isWakeUp: false}

刪除物件資料

使用 delete(一元運算子) 來刪除物件裡的屬性
被刪除的物件值為 undefined (可以使用 undefined 結果做後續的利用)

let home = {
motherName: "Mary",
fatherName: "Tom",
dogs: 3,
isWakeUp: false
};

delete home.motherName;
delete home.dogs;
console.log(home); // {fatherName: "Tom", isWakeUp: false}
console.log(home.motherName); // undefined

--

--