[筆記] ES6
就不多講 ES6 是什麼了,下面是 ES6 一些新的語法筆記。
宣告變數
在 ES6 裡面可以用 const、let、var:
- const 常數、不希望改變的值
- var 與 let 的區別在於 scope(作用域)
- var functional scope
- let block scope
通常是建議全部改用 const 與 let,不要再用 var 了。
字面模版(Template Literal)
本來要寫成 'hello' + name + '!'
,現在只要用 `hello ${name} !`
就可以了。
使用重音符號、反引號(backtick)與 ${}
。
解構(Destructuring)
ES5 以前要這樣寫:
var arr = [1, 2, 3] |
ES6 可以這樣寫:
const arr = [1, 2, 3] |
物件同理,而且可以用 key 來取值:
const obj = { |
還可以巢狀解構
展開(Spread Operator)
...
可以把陣列或物件展開,其實就是把它們的中括號([]
)或大括號({}
)拿掉,輸出裡面的內容。
以下幾個例子:
// 合併兩個陣列 |
// 將陣列中的值傳入函式 |
可以應用在複製陣列或物件的內容,而不會對原來的陣列或物件造成影響,因為指向的是不同記憶體位置了。
let arr1 = [1, 2, 3] |
反向展開(Rest Parameters)
收合!...rest
(rest 可以換成其它變數名稱)
常常與解構(Destructuring)一起用,例如:
let arr = [1, 2, 3] |
但是 ...rest
只能放在最後面的位置
同樣可以用在物件上:
let obj = { |
還可以在函式裡傳入參數時應用:
function add(...args) { |
設定預設值(Default Parameter)
ES5 設定預設值寫法:
function repeat (str, times) { |
ES6 寫法:
function repeat(str = 'hello', times = 3) { |
也可以運用於陣列或物件上。
箭頭函式(arrow function)
是一種語法糖(syntaxe sugar)
function repeat (str, times) { |
與陣列方法合用:
let arr = [1, 2, 3, 4] |
about this
;箭頭函式的 ‘this’ 有一些特殊性質,需要另外再去研究。
Import/Export
Export 有幾種方式:
export function add(){}
;使用import {add}
引入export { add }
;同樣使用import {add}
引入export default function add()
;使用import add
引入,不需要加大括號
如果想要用其他名字,可以用as
取別名,例如說export { add as addFunction }
可以用 import * as utils from 'utils'
把全部都 import 進來
Babel
因為有些 ES6 的語法現在很多地方還不支援(如 import export),所以可以讓 Babel 幫忙翻譯成 ES5 或其它更舊的語法。
可以安裝 babel-node
來測試,通常不會用 bable-node
在 production 上,效能不太好。npm install --save-dev @babel/core @babel/node
然後必需先後有前置設定:
npm install --save @babel/preset-env
- 建立
.babelrc
,內容為:然後就可以執行{
"presets": ["@babel/preset-env"]
}npx babel-node 檔案名
來運行了。