
继原来的 JavaScript hacks之后,这儿有了些新的点子。在2018年码JavaScript其实是件非常有趣的事情。
Hack #1 — 交换变量
用数组解构交换值。
1 2 3 4 5 6
| let a = 'world', b = 'hello'; [a, b] = [b, a]; console.log(a); console.log(b);
|
Hack #2 — Async/Await解构
数组解构非常好用,结合async/await
去实现一个复杂的流程变得很简单。
1 2 3 4
| const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ]);
|
Hack #3 — 调试
很多人喜欢用console.log
来调试,对这些人来说,下边的例子就是福音(是的,还有console.table
):
1 2 3 4 5 6 7 8 9
| const a = 5, b = 6, c = 7; console.log({a, b, c});
|
Hack #4 — 一行流
对于数组的运算,语法可以非常的紧凑。
1 2 3 4 5 6 7
| const max = (arr) => Math.max(...arr); max([123, 321, 32]);
const sum = (arr) => arr.reduce((a, b) => (a + b), 0); sum([1, 2, 3, 4]);
|
Hack #5 — 数组链接
spread operator
可以用来代替concat
:
1 2 3 4 5 6 7 8 9 10
| const one = ['a', 'b', 'c']; const two = ['d', 'e', 'f']; const three = ['g', 'h', 'i'];
const result = one.concat(two, three);
const result = [].concat(one, two, three);
const result = [...one, ...two, ...three];
|
Hack #6 — 复制
轻松克隆数组和对象:
1 2
| const obj = {...oldObj}; const arr = [...oldArr];
|
注意:这会创建一个浅拷贝。
Hack #7 — 命名参数
通过解构使函数和函数调用更易读:
1 2 3 4 5 6 7 8 9 10 11 12 13
| const getStuffNotBad = (id, force, verbose) => { };
const getStuffAwesome = ({ id, name, force, verbose }) => { };
getStuffNotBad(150, true, true)
getStuffAwesome({ id: 150, force: true, verbose: true })
|
原文:7 Hacks for ES6 Developers
作者:Tal Bereznitskey
译者:Elly