原文: 7 Hacks for ES6 Developers译者:neal1991javascript
welcome to star my articles-translator , providing you advanced articles translation. Any suggestion, please issue or contact mejava
LICENSE: MITgit
关注原来的 JavaScript hacks,上面有一些新的好东西。2018 使用 JavaScript 写代码真的又变得有意思了!es6
使用数组结构来交换值github
let a = 'world', b = 'hello' [a, b] = [b, a] console.log(a) // -> hello console.log(b) // -> world // 是的,很神奇
再说一遍,数组结构真的很棒。经过和 async/await 以及 promise 结合能够让复杂的流程变得简单。数组
const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ])
对于那些喜欢使用 console.logs 来调试的人来讲,如今有一些特别酷的(而且我也据说过 console.table):promise
const a = 5, b = 6, c = 7 console.log({ a, b, c }) // 输出优雅的对象: // { // a: 5, // b: 6, // c: 7 // }
对于数组操做,语法能够很是紧凑async
// 寻找最大值 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:函数
const one = ['a', 'b', 'c'] const two = ['d', 'e', 'f'] const three = ['g', 'h', 'i'] // 老方法 #1 const result = one.concat(two, three) // 老方法 #2 const result = [].concat(one, two, three) // 新方法 const result = [...one, ...two, ...three]
轻松克隆数组和对象:fetch
const obj = { ...oldObj } const arr = [ ...oldArr ]
注意:这会产生一个浅克隆。
经过结构让函数以及函数函数调用更具备可读性:
const getStuffNotBad = (id, force, verbose) => { ...do stuff } const getStuffAwesome = ({ id, name, force, verbose }) => { ...do stuff } // 在代码的其它某个地方... 到底什么是 true, true? getStuffNotBad(150, true, true) // 在代码的其余某个地方.. I ❤ JS!!! getStuffAwesome({ id: 150, force: true, verbose: true })
已经所有知道了?
你是一个真正的黑客,让咱们继续在 Twitter上的谈话你还能够看看个人 Torii 教学,咱们让“SaaS 头痛”消失。