首頁  >  文章  >  web前端  >  ES6中超實用的幾個技巧總結

ES6中超實用的幾個技巧總結

不言
不言轉載
2018-12-04 17:17:272008瀏覽

這篇文章帶給大家的內容是關於ES6中超實用的幾個技巧總結,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

Hack #1 交換元素

利用陣列解構來實作值的互換

let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world

Hack #2 偵錯

我們經常使用console.log()來進行調試,試試console.table()也無妨。

const a = 5, b = 6, c = 7
console.log({ a, b, c });
console.table({a, b, c, m: {name: 'xixi', age: 27}});

Hack #3 單一語句

ES6時代,操作陣列的語句將會更加的緊湊

// 寻找数组中的最大值
const max = (arr) => Math.max(...arr);
max([123, 321, 32]) // outputs: 321
// 计算数组的总和
const sum = (arr) => arr.reduce((a, b) => (a + b), 0)
sum([1, 2, 3, 4]) // output: 10

#Hack #4 陣列拼接

展開運算子可以取代concat的地位了

const one = ['a', 'b', 'c']
const two = ['d', 'e', 'f']
const three = ['g', 'h', 'i']
const result = [...one, ...two, ...three]

#Hack #5 製作副本

我們可以很容易的實作數組和物件的淺拷貝

const obj = { ...oldObj }
const arr = [ ...oldArr ]

Hack #6 命名參數

#解構使得函數宣告和函數的呼叫更可讀

// 我们尝尝使用的写法
const getStuffNotBad = (id, force, verbose) => {
 ...do stuff
}
// 当我们调用函数时, 明天再看,尼玛 150是啥,true是啥
getStuffNotBad(150, true, true)
// 看完本文你啥都可以忘记, 希望够记住下面的就可以了
const getStuffAwesome = ({id, name, force, verbose}) => {
 ...do stuff
}
// 完美
getStuffAwesome({ id: 150, force: true, verbose: true })

# Hack #7 Async/Await結合數組解構

數組解構非常讚!結合Promise.all和解構和await會使程式碼變得更加的簡潔

const [user, account] = await Promise.all([
 fetch('/user'),
 fetch('/account')
])


#

以上是ES6中超實用的幾個技巧總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除
上一篇:zepto是什麼下一篇:zepto是什麼