无脑翻译走一波~
Hack #1 — 变量交换
使用数组解构交换变量的值
let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world
// Yes, it's magic
Hack #2 — 解构 Async/Await
再强调一遍,数组解构非常好用。结合 async/await
与promises
能让复杂的流程变得简单。
const [user, account] = await Promise.all([
fetch('/user'),
fetch('/account')
])
Hack #3 — 调试
对于任何喜欢用console.log
进行调试的人来说,这都是一个好方法(当然,用console.table
也可以):
const a = 5, b = 6, c = 7
console.log({ a, b, c })
// outputs this nice object:
// {
// a: 5,
// b: 6,
// c: 7
// }
Hack #4 — 一行代码
操作数组时,这会让代码结构变得更为紧凑
// Find max value
const max = (arr) => Math.max(...arr);
max([123, 321, 32]) // outputs: 321
// Sum array
const sum = (arr) => arr.reduce((a, b) => (a + b), 0)
sum([1, 2, 3, 4]) // output: 10
Hack #5 — 连接数组
使用展开运算符...
代替 concat
:
const one = ['a', 'b', 'c']
const two = ['d', 'e', 'f']
const three = ['g', 'h', 'i']
// Old way #1
const result = one.concat(two, three)
// Old way #2
const result = [].concat(one, two, three)
// New
const result = [...one, ...two, ...three]
Hack #6 — 复制
下面的方法用于复制(浅复制)数组/对象:
const obj = { ...oldObj }
const arr = [ ...oldArr ]
Hack #7 —命名参数
解构命名参数,提升函数声明和函数调用的可读性:
const getStuffNotBad = (id, force, verbose) => {
...do stuff
}
const getStuffAwesome = ({ id, name, force, verbose }) => {
...do stuff
}
// Somewhere else in the codebase... WTF is true, true?
getStuffNotBad(150, true, true)
// Somewhere else in the codebase... I ❤ JS!!!
getStuffAwesome({ id: 150, force: true, verbose: true })
阅读原文:https://medium.com/dailyjs/7-hacks-for-es6-developers-4e24ff425d0b