簡評:ES6(ECMAScript2015)其實是一種新的 JavaScript
規範,包含了一些很棒的新特性,能夠更加方便地實現不少複雜的操做。
先看一下 ES6 的新特性:es6
Hack #1: Swap variables 交換變量數組
使用 Array Destructuring 交換值異步
let a = 'world', b = 'hello' [a, b] = [b, a] console.log(a) // -> hello console.log(b) // -> world // Yes, it's magic
Hack #2 : Async/Await with Destructuring函數
下面這段代碼能夠同時發起兩個異步請求,把請求結果分別附到 user 和 account 中fetch
const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ])
Hack #3 : Debuggingthis
const a = 5, b = 6, c = 7 console.log({ a, b, c }) // outputs this nice object: // { // a: 5, // b: 6, // c: 7 // }
Hack #4 : One linersspa
更緊湊的數組操做語法code
// Find max value const max = (arr) => Math.max(...arr); max([123, 321, 32]) // outputs: 321 // Sum array const sum = (arr) => arr.reduce((a, b) => (a + b), 0) sum([1, 2, 3, 4]) // output: 10
Hack #5 : Array concatenation對象
展開運算符能夠用來代替 concatblog
const one = ['a', 'b', 'c'] const two = ['d', 'e', 'f'] const three = ['g', 'h', 'i'] // Old way #1 const result = one.concat(two, three) // Old way #2 const result = [].concat(one, two, three) // New const result = [...one, ...two, ...three]
Hack #6 : Cloning
const obj = { ...oldObj } const arr = [ ...oldArr ]
Hack #7 : Named parameters 參數命名
const getStuffNotBad = (id, force, verbose) => { ...do stuff } const getStuffAwesome = ({ id, name, force, verbose }) => { ...do stuff } // Somewhere else in the codebase... WTF is true, true? getStuffNotBad(150, true, true) // Somewhere else in the codebase... I ❤ JS!!! getStuffAwesome({ id: 150, force: true, verbose: true })
原文連接: 7 Hacks for ES6 Developers