# 需要知道的語法糖 Syntactic sugar|筆記 by Sz ###### tags: `Sz` `課前` `Vue新手夏令營` - [Vue 新手夏令營 課程頁面](https://hackmd.io/@dbFY0UD9SUeKmNXhWf01ew/BkJoW-hn_/%2FC05go-8iTSS-nrMwKU22kA) - [:sun_with_face:筆記入口](/2JiZbCPdR0G4p5fNycPmTg) :::info 介紹幾個 ES6 版本中,有幾個語法糖 - Object 的「物件字面值 Object Literals」語法糖 - function 簡寫 - 與 arrow function 的不同 - 變數簡寫 - 展開 - 陣列的展開 - 物件的展開 - 在空陣列裡展開取得純陣列功能 - function 的預設值 ::: ## 物件字面值 字面上物件長什麼樣子的意思 ``` const obj = { key: value } ``` ## Object 內的 function 屬性 ### 原本寫法 ``` funName: function() { return this; }; ``` ### ES6 語法糖 ``` funName() { // 直接省略 :function return this; }; ``` :::danger ### 注意: arrow function 是不一樣的 `this` 指向不同,需注意,不該與語法糖混為一談(`this` 等下一篇再來講) ``` funName: () => { return this; }; ``` ::: ## 變數簡寫 ### 原本寫法 ``` const person = { name: '小明' }; const people = { person: person } ``` ### ES6 語法糖 導入物件 A 到 B 物件當 value 時,如果屬性與 value 同名,則可以簡寫 ``` const person = { name: '小明' }; const people = { person // 直接省略 key } ``` ## 展開 ### 陣列擴展,不同陣列合併 #### 原本寫法 ```` const aryA = [1, 2, 3]; const aryB = [4, 5]; const aryAll = aryA.concat(aryB); ```` #### 語法糖:[...aryA, ...aryB] ```` const aryA = [1, 2, 3]; const aryB = [4, 5]; const aryAll = [...aryA, ...aryB] ```` ### 物件擴展,導入更多物件 將 object 內容直接展開新增到另一個 object ``` const methods = { fnA() {}, fnB() {} } const newMethods = { ...methods } ``` ### 轉成純陣列 比如說使用 querySelectorAll 時,雖然一樣是 array 形式,但可以用的動作(`__proto__` 裡面)比較少,實務上很常需要把它轉回純的 array ``` // 取得複數個 li 的 array const allLi = document.querySelectorAll('li'); // 讓他在新的 array 裡展開,取得純陣列可使用的__proto const newAllLi = [...allLi]; ``` ## function 預設值 function 可以預設 argument 的 value,不需要每次呼叫都重填 ``` function sum(a, b = 2) { return a + b; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up