Hack #1 交換元素
利用 數(shù)組解構(gòu)來(lái)實(shí)現(xiàn)值的互換
let a = 'world', b = 'hello'[a, b] = [b, a]console.log(a) // -> helloconsole.log(b) // -> world
Hack #2 調(diào)試
我們經(jīng)常使用 console.log()來(lái)進(jìn)行調(diào)試,試試 console.table()也無(wú)妨。
const a = 5, b = 6, c = 7console.log({ a, b, c });console.table({a, b, c, m: {name: 'xixi', age: 27}});Hack #3 單條語(yǔ)句
ES6時(shí)代,操作數(shù)組的語(yǔ)句將會(huì)更加的緊湊
// 尋找數(shù)組中的最大值const max = (arr) => Math.max(...arr);max([123, 321, 32]) // outputs: 321// 計(jì)算數(shù)組的總和const sum = (arr) => arr.reduce((a, b) => (a + b), 0)sum([1, 2, 3, 4]) // output: 10
Hack #4 數(shù)組拼接
展開(kāi)運(yùn)算符可以取代 concat的地位了
const one = ['a', 'b', 'c']const two = ['d', 'e', 'f']const three = ['g', 'h', 'i']const result = [...one, ...two, ...three]
Hack #5 制作副本
我們可以很容易的實(shí)現(xiàn)數(shù)組和對(duì)象的 淺拷貝
const obj = { ...oldObj }const arr = [ ...oldArr ]Hack #6 命名參數(shù)👍👍👍
解構(gòu)使得函數(shù)聲明和函數(shù)的調(diào)用更加可讀
// 我們嘗嘗使用的寫法const getStuffNotBad = (id, force, verbose) => { ...do stuff}// 當(dāng)我們調(diào)用函數(shù)時(shí), 明天再看,尼瑪 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結(jié)合數(shù)組解構(gòu)
數(shù)組解構(gòu)非常贊!結(jié)合 Promise.all和 解構(gòu)和 await會(huì)使代碼變得更加的簡(jiǎn)潔
const [user, account] = await Promise.all([ fetch('/user'), fetch('/account')])總結(jié)
以上所述是小編給大家介紹的分享ES6的7個(gè)實(shí)用技巧,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)錯(cuò)新站長(zhǎng)站網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選