ES6 总结

248 阅读1分钟

ES6 总结

ECMAScript 6 入门

1. 变量

var 能够重复声明, 是函数级作用域

let 不能重复声明, 是块级作用域, 变量

const 不能重复声明, 是块级作用域, 常量

2. 箭头函数

a. 方遍

  • 如果只有一个参数, 可以省略 ()
  • 如果只有一行, 可以省略 return
a => { a+=1; }

b. 解决this 的问题

3. 参数扩展

a. 参数搜集

function test(a, b, ...args){}

b. 参数扩展

function test(a, b, ...args){
    console.log(...args);
}

c. 默认参数

function test(a, b, c=1){}

4. 数组方法

  • map 数组映射
const arr = [1,2,3];
const res = arr.map(x=>x*2);
// res => [2,4,6]
  • filter 数组筛选
const arr = [1,2,3];
const res = arr.filter(x=>x>2);
// res => [3]
  • reduce 归总
const arr = [1,2,3];
const res = arr.reduce((sum, i)=>sum+i, 0);
// res => 6
  • forEach 迭代
const arr = [1,2,3];
const res = arr.forEach(x => {
    console.log(x)
});
// 1,2,3

5. 字符串

  • startsWith/endsWith
'12345'.startsWith('12');
// true
  • 字符串模板
const name = 'Hosea';
console.log(`hi: ${name}`);
// hi: Hosea

6. Promise

执行异步操作,在同时需要执行多个异步操作的时候很好用。

  • Promise.all() 一次执行多个,所有的异步结束后返回所有的结果集。
    Promise.all([
        new Promise(),
        new Promise(),
        ...
    ])
    .then((res)=>{
        console.log(res);
    }})
    .catch((err)=>{
        console.log(err);
    })
  • Promise.race()

一次执行多个,返回第一个完成异步的结果。

7. generater

函数执行时遇到 yield 会暂停, 直到调用 .next 方法

function* dataConsumer() {
  console.log('Started');
  console.log(`1. ${yield}`);
  console.log(`2. ${yield}`);
  return 'result';
}

let genObj = dataConsumer();
genObj.next();
// Started
genObj.next('a')
// 1. a
genObj.next('b')
// 2. b

因为 generater 遇到 yield 会暂停, 所以可以实现 类似 async/await 的用法。

8. 面向对象

// 定义类
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

// 类的继承
class Bar extends Point {
    constractor(...args){
        super(...args);
    }
}

9. 解构赋值

let [a, b, c] = [1, 2, 3];