DAY 12
2
Modern Web

## 物件

### 解構賦值

#### 取出物件某值

``````var grade = {
chinese: 85,
math: 90
};

var { chinese } = grade;
console.log(chinese); // 85
``````

``````var { chinese, math } = grade;
console.log(chinese, math); // 85 90
``````

``````var grade = {
chinese: 85,
math: 90
};

var { chinese: myChinese } = grade;
console.log(myChinese); // 85
``````

#### 結合陣列

``````var { fruit: [, Q1] } = {
fruit: ['apple', 'banana', 'orange']
}

console.log(Q1); // Q1=?
``````

Ps. 忘記的話可以參考 Day9

Ans:
`Q1` = banana

### 縮寫

1. 屬性的名稱一樣，則可省略後者
``````var a = 123;
var b = {
a: a
};

// 可縮寫為
var b = {
a
}
``````
1. 函數也可以縮寫
``````var a = {
sayHi: function(){
console.log("Hi");
}
}

// 可縮寫為
var a = {
sayHi () {
console.log("Hi");
}
}
``````

#### 搭配縮寫與延展的深拷貝

Ps. 關於較詳細的介紹可以看 Day11

``````var a = {
age: 18
}
var b = {
...a
}

b.age = 20;

console.log(a.age); // 18
console.log(b.age); // 20
``````

### For in 取值

``````var myObj = {
name: "Ray",
age: 18
};

for(var key in myObj){
console.log("key: " + key + " value: " + myObj[key]);
}
// key: name value: Ray
// key: age value: 18
``````

``````var myObj = {
class1: {
num: 30
},
class2: {
num: 35
}
}

for(var key in myObj){
console.log("key: " + key + " value: " + myObj[key].num);
}
// key: class1 value: 30
// key: class2 value: 35
``````