jas0nhuang

[筆記] 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]
var num1 = arr[0]
var num2 = arr[1]
var num3 = arr[2]

ES6 可以這樣寫:

const arr = [1, 2, 3]
let [num1, num2, num3]

物件同理,而且可以用 key 來取值:

const obj = {
name: 'kick',
age: 38,
home: 'TW',
}
let {home} = obj
console.log(home) // 'TW'

還可以巢狀解構

展開(Spread Operator)

...
可以把陣列或物件展開,其實就是把它們的中括號([])或大括號({})拿掉,輸出裡面的內容。
以下幾個例子:

// 合併兩個陣列
let arr = [1, 2, 3]
let arr2 = [4, 5,...arr, 6]
console.log(arr2) // [4, 5, 1, 2, 3, 6]
// 將陣列中的值傳入函式
function add(a, b, c) {
return a + b + c
}
let arr = [1, 2, 3]
console.log(add(...arr)) // 6

可以應用在複製陣列或物件的內容,而不會對原來的陣列或物件造成影響,因為指向的是不同記憶體位置了。

let arr1 = [1, 2, 3]
let arr2 = [...arr1]
arr2.push(4)
console.log(arr1) // [1, 2, 3]
console.log(arr2) // [1, 2, 3, 4]

反向展開(Rest Parameters)

收合!
...rest (rest 可以換成其它變數名稱)
常常與解構(Destructuring)一起用,例如:

let arr = [1, 2, 3]
let [first, ...rest] = arr
console.log(first) // 1
console.log(rest) // [2, 3]

但是 ...rest 只能放在最後面的位置
同樣可以用在物件上:

let obj = {
a: 1,
b: 2,
c: 3,
}
let {a, ...obj2} = obj
console.log(obj2) // {b:2, c:3}

還可以在函式裡傳入參數時應用:

function add(...args) {
console.log(args)
return args[0] + args[1]
}
console.log(add(1,2)) // [1, 2] 3

設定預設值(Default Parameter)

ES5 設定預設值寫法:

function repeat (str, times) {
str = str || 'hello'
times = times || 3
return str.repeat(times)
}

ES6 寫法:

function repeat(str = 'hello', times = 3) {
return str.repeat(times)
}

也可以運用於陣列或物件上。

箭頭函式(arrow function)

是一種語法糖(syntaxe sugar)

function repeat (str, times) {
return str.repeat(times)
}
// to
let repeat = (str, times) => str.repeat(times)

與陣列方法合用:

let arr = [1, 2, 3, 4]
console.log(
arr
.filter(function(value) {
return value > 1
})
.map(function(value) {
return value * 2
})
)
// 可改寫為:
arr
.filter(value => value > 1)
.map(value => value * 2)

about this;箭頭函式的 ‘this’ 有一些特殊性質,需要另外再去研究。

Import/Export

  • Export 有幾種方式:

    1. export function add(){};使用 import {add} 引入
    2. export { add };同樣使用 import {add} 引入
    3. 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 檔案名 來運行了。