---
# System prepended metadata

title: JS Chapter4_物件
tags: [JS鐵人賽]

---

# JS Chapter4_物件
###### tags: `JS鐵人賽`
 
### 物件使用時機
詳細描述一個東西內部資訊

### 物件格式

```javascript=
//物件格式
let home = {
    //屬性 : '值',
    //屬性 : '值',
    motherName : 'Mary',
    fatherName : 'Tom',
    isWakeUp : 'False',
    dogs : 3,
};
```

### 讀取物件

```javascript=
let home = {
    motherName : 'Mary',
    fatherName : 'Tom',
    isWakeUp : 'False',
    dogs : 3,
};
//讀取物件值
let tomDogs = home.dogs;
console.log(tomDogs);
```
```javascript=
//另一種讀取方式－字串
console.log('motherName')
```
```javascript=
//讀取進階用法
let a = 'motherName';
console.log(home[a])
```
如果面臨到需要讀取Json資料則會如以下情況
```javascript=
//json陣列寫法
let home = {
myName : 'Jack',
'001' : 'Mary',
};

console.log(home);

//想讀取001資料不得用此方式→console.log(home.001);
console.log(home['001']);

```



### 新增物件屬性
```javascript=
let home = {};
home.myName = 'Mary';
home.dogs = 3;
home.isWakeup = false;
console.log(home);
```

### 修改物件值
```javascript=
let home = {
    motherName : 'Mary',
    fatherName : 'Tom',
    isWakeUp : 'False',
    dogs : 3,
};

//修改物件值
home.motherName = 'Jane';
home.dogs+=1;
console.log(home);

```

### 刪除物件值
```javascript=
let home = {
    motherName : 'Mary',
    fatherName : 'Tom',
    isWakeUp : 'False',
    dogs : 3,
};

delete home.dogs;
console.log(home);

//由於dogs值被刪除，因此會顯示undefined
console.log(home.dogs);

```

### 使用鍵值操作物件
https://www.delftstack.com/zh-tw/howto/javascript/javascript-key-value-array/

https://ithelp.ithome.com.tw/articles/10219496

**進階操作DEMO－使用函數回傳物件**
https://codepen.io/TODelusion/pen/qBxwzMX?editors=0012



