[译]7个ES6编程小技巧

238 阅读1分钟

1. 交换变量

使用数组解构来交换变量的值

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});
// 输出
//{
//	a: 5,
//	b: 6,
//	c: 7
//}

4. 一行解决

对于某些数组操作,可以使用更为简洁的语法

//找出最大值
const max = (arr) => Math.max(...arr);
max([123, 321, 23]); //输出 321

//数组求和
const sum = (arr) => arr.reduce((a, b) => (a + b), 0);
sum([1, 2, 3, 4]); //输出 10

5. 数组合并

扩展操作符可以用来代替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];

6. 克隆

const obj = { ...oldObj };
const arr = [ ...oldArr ];

注:以上方法创建的是一个浅克隆

7. 命名参数

通过使用解构操作符让函数更易读:

const getStuffNotBad = (id, force, verbose) => {
	...
}
const getStuffAwesome = ({ id, name, force, verbose } => {
	...
})

//这种方法让人一时不知道这个几个参数表示的是什么
getStuffNotBad(150, true, true);

//参数意思一目了然
getStuffAwesome({ id: 150, force: true, verbose: true });

阅读原文