分享ES6的7個實用技巧
Hack #1 交換元素
利用 數(shù)組解構來實現(xiàn)值的互換
let a = 'world', b = 'hello' [a, b] = [b, a] console.log(a) // -> hello console.log(b) // -> world
Hack #2 調(diào)試
我們經(jīng)常使用 console.log()來進行調(diào)試,試試 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時代,操作數(shù)組的語句將會更加的緊湊
// 尋找數(shù)組中的最大值 const max = (arr) => Math.max(...arr); max([123, 321, 32]) // outputs: 321 // 計算數(shù)組的總和 const sum = (arr) => arr.reduce((a, b) => (a + b), 0) sum([1, 2, 3, 4]) // output: 10
Hack #4 數(shù)組拼接
展開運算符可以取代 concat的地位了
const one = ['a', 'b', 'c'] const two = ['d', 'e', 'f'] const three = ['g', 'h', 'i'] const result = [...one, ...two, ...three]
Hack #5 制作副本
我們可以很容易的實現(xiàn)數(shù)組和對象的 淺拷貝
const obj = { ...oldObj } const arr = [ ...oldArr ]
Hack #6 命名參數(shù)👍👍👍
解構使得函數(shù)聲明和函數(shù)的調(diào)用更加可讀
// 我們嘗嘗使用的寫法 const getStuffNotBad = (id, force, verbose) => { ...do stuff } // 當我們調(diào)用函數(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結合數(shù)組解構
數(shù)組解構非常贊!結合 Promise.all和 解構和 await會使代碼變得更加的簡潔
const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ])
總結
以上所述是小編給大家介紹的分享ES6的7個實用技巧,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
TensorFlow.js 微信小程序插件開始支持模型緩存的方法
這篇文章主要介紹了TensorFlow.js 微信小程序插件開始支持模型緩存的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02URLSearchParams快速解析URL查詢參數(shù)實現(xiàn)
這篇文章主要為大家介紹了URLSearchParams快速解析URL查詢參數(shù)實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06JavaScript實現(xiàn)單擊網(wǎng)頁任意位置打開新窗口與關閉窗口的方法
這篇文章主要介紹了JavaScript實現(xiàn)單擊網(wǎng)頁任意位置打開新窗口與關閉窗口的方法,涉及javascript窗口的相關操作函數(shù)與使用技巧,需要的朋友可以參考下2017-09-09