---
# System prepended metadata

title: 第 23 節： Newer JavaScript Features
tags: [The Web Developer Bootcamp 2021, JavaScript, Udemy]

---

Udemy課程：[The Web Developer Bootcamp 2021（Colt Steele）](https://www.udemy.com/course/the-web-developer-bootcamp/)
# 第 23 節： Newer JavaScript Features
###### tags: `JavaScript` `Udemy` `The Web Developer Bootcamp 2021`
2021.03.10（Wed.）～03.17（Wed.）
## ● 上課筆記

## 1. Default parameters（預設參數）
在 JavaScript 中，函式的參數預設值都為 undefined 。

以往設定預設值有個普遍方法：在函式的內容裡檢查傳入參數是否為 undefined ，如果是的話，爲他指定一個值。
* 範例：
```javascript=
function rollDie(numSides){
    if(numSides === undefined){
        numSides = 6
    }
    return Math.floor(Math.random()*numSides) + 1
}
```

The new way！新的方法如下！
* 範例：
```javascript=
function rollDie(numSides = 6){
    return Math.floor(Math.random()*numSides) + 1
}
```

## 2. Spread Operator（展開運算子）
> 參考網址：[JavaScript ES6 中的展開運算子（spread operator）和其餘運算子（rest operator）](https://pjchender.blogspot.com/2017/01/es6-spread-operatorrest-operator.html)

* 範例：
展開運算子可以把陣列中的元素取出。
```javascript=
//1：數字
const nums = [1,2,3,4,5]
Math.max(nums)        //NaN
Math.max(...nums)     //5

console.log(nums)     //[1,2,3,4,5]
console.log(...nums)  //1 2 3 4 5

//2：字串
console.log("Hello")             //Hello
console.log(..."Hello")          //H e l l o
console.log('H','e','l','l','o') //H e l l o
```
* Spread in array literals
Creat a new array using an existing array.Spreads the elements from one array into a new array.
```javascript=
const nums1 = [1,2,3]
const nums2 = [4,5,6]

console.log([...nums1, ...nums2])
//[1,2,3,4,5,6]

console.log(["a","b", ...nums2])
//["a","b",4,5,6]

console.log([...nums1, ...nums2,7,8,9])
//[1,2,3,4,5,6,7,8,9]
```

* Spread in object literals
Copies propertites from one object into another object literal.
```javascript=
const feline = {legs:4, family:"Felidae"}
const canine = {family:"Caninae", furry:true}

const dog = {...canine, isPet:true}
//{family:"Caninae", furry:true, isPet:true}

const lion = {...feline, genus:"Panthera"}
//{legs:4, family:"Felidae", genus:"Panthera"}

const catDog = {...feline, ...canine}
//{legs:4, family:"Felidae", family:"Caninae", furry:true}
```

## 3. Rest Parameter（其餘參數、剩餘參數）
> 長得很像展開運算子，但他不是！
> It looks like spread,but it's not.
> 
> 參考網站：[Day08【ES6 小筆記】剩餘參數 - 基礎使用範例（Rest parameter）](https://ithelp.ithome.com.tw/articles/10214394)

其餘參數（rest parameter） 語法可以讓我們表示不確定數量的參數，並將其視為一個陣列。白話一點就是當function有不確定數量的參數時，ES6 提供的「剩餘參數」就可以幫助我們很容易 取得剩餘的所有參數，並保存在陣列裡。

意思是，假如我參數先用nums好了，那麼我的sum( )裡面就只能放一個參數：
```javascript=
function sum(nums){
    console.log(nums)
}

sum(3) //不能再多放
```

所以如果我像要放多個參數，又不能確定要幾個參數時，就可以使用rest parameter了！
```javascript=
function sum(...nums){
    console.log(nums)
}

sum(3,5,7,9) //無論放幾個都可以的！
```

* 範例：
```javascript=
function raceResults(gold, silver, ...everyoneElse){
    console.log(`Gold medal goes to: ${gold}`)
    console.log(`Silver medal goes to: ${silver}`)
    console.log(`And thanks to everyone else: ${everyoneElse}`)
}

raceResults("Tammy","Todd","Tina","Trevor","Travis")
//Gold medal goes to: Tammy
//Silver medal goes to: Todd
//And thanks to everyone else: Tina,Trevor,Travis
```

## 4. 展開運算子（spread operator）和其餘運算子（rest operator）


| 名稱 | 內容比較 |
| ---- | -------- |
| 展開運算子（spread operator） |把陣列中的元素取出|
| 其餘運算子（rest operator）   |把輸入函式中的參數值變成陣列的形式|

## 5. Destructuring assignment（解構賦值）
> 參考網址：[Day 08: ES6篇 - Destructuring Assignment(解構賦值)](https://ithelp.ithome.com.tw/articles/10185430)

解構賦值 (Destructuring assignment) 語法是一種 JavaScript 運算式，可以把陣列或物件中的資料解開擷取成為獨立變數。

* 從陣列解構賦值(Array destructuring)
用來賦值的等號符號(=)左邊按照你寫的變數或常數樣式，然後在右邊寫上要對映數值，就像之前說的"鏡子"般的樣式映對。當沒有對應位置的值時，就會被指定為undefined。
```javascript=
const scores = [90000000,80000000,7000000,60000000,50000000]

const [gold, silver, bronze, ...everyoneElse] = scores
console.log(gold) //90000000
console.log(silver) //80000000
console.log(bronze) //70000000
console.log(everyoneElse) //[60000000,50000000]
```

* 從物件解構賦值(Object destructuring)
```javascript=
const user = {
    email: "harvey@gmail.com",
    password:"sCoTt1948sMiTh",
    firstName:"Harvey",
    lastName:"Milk",
    born: 1930,
    died: 1978,
    bio: "American politician",
    city: "San Francisco",
    state: "California"
}

//-----體取user資料中的email-----//
//一般方法：
const email = user.email
//Object destructuring方法：
const {email} = user
console.log(email) //harvey@gmail.com

//其餘用法：
const {email, firstName, lastName, city, bio} = user
console.log(email) //harvey@gmail.com
console.log(firstName) //Harvey
console.log(lastName) //Milk
console.log(city) //San Francisco
console.log(bio) //American politician

//若想要重新命名：
//如下所示，則將born存於新變數名birthYear
const {born: birthYear} = user
console.log(born) //born is not defined
console.log(birthYear) //1930
```
* Destructuring Params
```javascript=
const movies = [
    {
        title: 'Amadeus',
        score: 99,
        year: 1984
    },
    {
        title: 'Sharknado',
        score: 35,
        year: 2013
    },
    {
        title: '13 Going On 30',
        score: 70,
        year: 2004
    },
    {
        title: 'Stand By Me',
        score: 85,
        year: 1986
    },
    {
        title: 'Waterworld',
        score: 62,
        year: 1995
    },
    {
        title: 'Jingle All The Way',
        score: 71,
        year: 1996
    },
    {
        title: 'Parasite',
        score: 95,
        year: 2019
    },
    {
        title: 'Notting Hill',
        score: 77,
        year: 1999
    },
    {
        title: 'Alien',
        score: 90,
        year: 1979
    }
]

//-----第一組比較-----//
//一般方法
movies.filter((movie) => movie.score >= 90)
//Destructuring Params方法
movies.filter(({ score }) => score >= 90)

//-----第二組比較-----//
//一般方法
movies.map(movie => {
    return `${movie.title} (${movie.year}) is rated ${movie.score}`
 })
 //Destructuring Params方法
movies.map(({ title, score, year }) => {
    return `${title} (${year}) is rated ${score}`
})
```