7 Hacks for ES6 Developers
利用數組解構
來實現值的互換es6
let a = 'world', b = 'hello' [a, b] = [b, a] console.log(a) // -> hello console.log(b) // -> world
咱們常用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}});
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
展開運算符能夠取代concat
的地位了segmentfault
const one = ['a', 'b', 'c'] const two = ['d', 'e', 'f'] const three = ['g', 'h', 'i'] const result = [...one, ...two, ...three]
咱們能夠很容易的實現數組和對象的淺拷貝
拷貝
數組
const obj = { ...oldObj } const arr = [ ...oldArr ]
拷貝
= 深拷貝
? 淺拷貝
?
好像有些朋友對這裏我說的淺拷貝
有些質疑,我也能理解你們所說的。下面數組爲例:瀏覽器
// 數組元素爲簡單數據類型非引用類型 const arr = [1, 2, 3, 4]; const newArr = [...arr];
// 數組元素爲引用類型 const person01 = {name: 'name01', age: 1}; const person02 = {name: 'name01', age: 2}; const person03 = {name: 'name03', age: 3}; const arr = [person01, person02, person03]; const newArr = [...arr]; console.log(newArr[0] === person01); // true
第二個 demo 就是我想表達的淺拷貝,如有不一樣意見歡迎討論~異步
解構使得函數聲明和函數的調用更加可讀編程語言
// 咱們嚐嚐使用的寫法 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 })
數組解構很是贊!結合Promise.all
和解構
和await
會使代碼變得更加的簡潔函數
const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ])
完全掌握 JS 異步處理 Promise 和 Async-Awaitfetch
【開發環境推薦】 Cloud Studio 是基於瀏覽器的集成式開發環境,支持絕大部分編程語言,包括 HTML五、PHP、Python、Java、Ruby、C/C++、.NET 小程序等等,無需下載安裝程序,一鍵切換開發環境。 Cloud Studio提供了完整的 Linux 環境,而且支持自定義域名指向,動態計算資源調整,能夠完成各類應用的開發編譯與部署。