省时省力的ES6

103 阅读2分钟
原文链接: www.liayal.com

人一懒起来啊,简直是………上一次发文章都是两个月前了:guardsman:

这次就收集一些ES6中的HACK吧!讲真的(会不会是..)…掌握这些技巧。能让我们少写很多行代码哦twemoji-1f427

1. 变量交换

let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world

// 双击666

2. 接收函数返回的多个结果

使用async/await,函数会把返回值放在一个数组中。使用数组解构后就可以把返回值直接赋给相应的变量。

const [user, account] = await Promise.all([
  fetch('/user'),
  fetch('/account')
])

3. 字符串拼接

let a = 'hello',
    b = 'world';

let _string = `${a} ${b}`

console.log(_string); // "hello world"

4. 函数参数默认值

const notify = (msg, {type='info', timeout, close=true} = {}) => {
  // display notification
    console.log(msg, type, timeout, close)
}

notify('Hi!'); // Hi! info undefined true
notify('Hi!', {type: 'error'}); // Hi! error undefined true
notify('Hi!', {type: 'warn', close: false}); // Hi! warn undefined false

5. 数组

代码不多一行搞定

// 最大值
const max = (arr) => Math.max(...arr);
max([1, 2, 3]) // outputs: 321

// 求和
const sum = (arr) => arr.reduce((a, b) => (a + b), 0)
sum([1, 2, 3, 4]) // output: 10

// 拷贝
let array1 = [1, "3", { a: 1}, 666];
let copyArray = [ ...array1 ];
console.log(copyArray) // [1, "3", {…}, 666]

// 数组连接
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. 去重

通过 Set 可以轻易的实现数组去重

function dedupe(array) {
return […new Set(array)];
}

let noDupes = dedupe([1, 2, “a”, “a”, { obj1: 999}, 7, 3, 1], { obj1: 999});

console.log(noDupes); // [1, 2, “a”, { obj1: 999}, 7, 3]

通过数组创建 Set 会删除数组中的重复项,而spread运算符会将 Set 转换为 Array

7. 强制要求参数

const throwIfMissing = () => {
    throw new Error('Missing parameter');
}
const func = (requiredParam = throwIfMissing()) => {
    // some implementation
}

8. 删除对象中不需要参数

let { boy1, boy2, ...others } = { boy1: "sunshine", boy2: "sunshine", girl1: "beautiful", girl2: "very beautiful", girl2: "very beautiful", girl2: "very very beautiful" };

console.log(others) // { girl1: "beautiful", girl2: "very beautiful", girl2: "very beautiful", girl2: "very very beautiful"}

9. 动态属性名

let name = "mael";

let me = {
    [`${name}`]: name,
    age: 24
};

10. for 循环

let a = ['a', 'b', 'c', 'd' ];
// ES6 
for ( var val of a ) {
    console.log( val );
} // "a" "b" "c" "d"
// ES5
for ( var idx in a ) {
    console.log( idx );
}  // 0 1 2 3

11. 定义抽象基类

抽象基类是一种专门用于继承的类。它不能直接构建。主要用例是继承的类具有公共接口。但是,class 尚未利用abstract关键字来创建抽象基类,我们可以使用new.target来模拟。

class Note {
    constructor() {
        if (new.target === Note) {
            throw new Error('Note cannot be directly constructed.')
        }
    }
}
class ColorNote extends Note {

}
let note = new Note();               // error!
let colorNote = new ColorNote();   // ok

12. 定义惰性范围函数

我们可以使用 generators 来创建一个惰性函数

function* range(start, count) {
    for (let delta = 0; delta < count; delta++) {
        yield start + delta;
    }
}

for (let teenageYear of range(13, 7)) {
    console.log(`Teenage angst @ ${teenageYear}!`);
}