7 个ES6 的 Hack 技巧
技巧1: 交换变量:
使用数组解构(Array Destructuring)
let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world
技巧2:使用Async/Await解构:
数组解构非常方便,结合Async/Await和Promise可以让复杂的工作流更加简单。
const [user, account] = await Promise.all([
fetch('/user'),
fetch('/account')
])
技巧3:Debugging:
如果你喜欢使用console.log调试的话,这个方法可能会令你非常喜欢:
const a = 5, b=6, c =7
console.log({a, b, c})
// outputs this nice object:
// {
// a: 5,
// b: 6,
// c: 7
// }
技巧4:One liners:
对于数组操作来说,语法可以更加紧凑。
//寻找最大值
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
技巧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]
技巧6:克隆(Cloning)
轻松地克隆数组和对象:(但是只是一个浅拷贝哦)
const obj = { ...oldObj }
const arr = [ ...oldArr ]
技巧7:参数命名(Named parameters)
使用解构可以使函数定义和调用可读性更高:
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 })