es6有哪些新特性

269 阅读4分钟
  • 变量:

    • let:
    • const:
  • 解构赋值

    • 数组的变量解构赋值:
      • 解构可以默认值:let [x, y = 'b'] = ['a']; // x='a', y='b'
      • 赋值:let [a, b, c] = [1, 2, 3];
    • 对象变量的结构赋值:
      • 解构:
        let obj = { first: 'hello', last: 'world' };
        let { first: f, last: l } = obj;
        f // 'hello'
        l // 'world'
        
      • 赋值:
        let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
        baz // "aaa"
        foo // error: foo is not defined
        
    • 字符串的解构赋值
      const [a, b, c, d, e] = 'hello';
          a // "h"
          b // "e"
          c // "l"
          d // "l"
          e // "o"
      
    • 其它:number Boolean function。
  • 字符串新增方法

    • 模板字符串。
    • 新增的方法:
      • codePointAt();
      • String.fromCodePoint();
      • normalize()
      • includes(), startsWith(), endsWith()
      • repeat()
      • padStart(),padEnd()
      • matchAll()
  • 正则构造函数: *

  • number新增方法:

    • Number.isFinite(),
    • Number.isNaN(),
    • Number.parseInt(),
    • Number.parseFloat(),
    • Number.isInteger(),
    • Number.EPSILON,
    • Number.isSafeInteger()
  • 函数扩展:

    • 箭头函数
    • 默认参数(和...其它参数(替代arguments))
    • 严格模式:函数内部'use strict'后就不可使用es6fu相关。
    • name属性:console.log(fun.name)返回函数名字
    • 双冒号运算符:等价于bind,
      foo::bar(...arguments);
      // 等同于
      bar.apply(foo, arguments);
      
    • 尾调
    • 尾递归
  • 数组新增方法:

    • 扩展运算符[...] 替代了apply
      // ES5 的写法
      function f(x, y, z) {
        // ...
      }
      var args = [0, 1, 2];
      f.apply(null, args);
      
      // ES6的写法
      function f(x, y, z) {
        // ...
      }
      let args = [0, 1, 2];
      f(...args);
      
      
      
    • Array.from(obj,fun):
      • 类数组对象转换成数组
      let arrayLike = {
          '0': 'a',
          '1': 'b',
          '2': 'c',
          length: 3
      };
      let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
      Array.from([1, 2, 3], (x) => x * x)
      // [1, 4, 9]
      
      
    • Array.of(any):将一组值转换为数组,返回新的数组
      Array.of(3, 11, 'sss') 
      
    • copyWithin(index,start,end):当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。
    // 将3号位复制到0号位
    [1, 2, 3, 4, 5].copyWithin(0, 3, 4)
    // [4, 2, 3, 4, 5]
    
    
    
    • find(fun(value,index,arr),obj) 和 findIndex(fun(value,index,arr),obj)
      • 这两个方法都可以发现NaN,弥补了数组的indexOf方法的不足。
      • find找出第一个符合条件的数组成员,否则返回undefined
      • findIndex(),如果找不到返回-1
    • fill(varlue,start,end)
      • 填充数组或者数组中对象:
      ['a', 'b', 'c'].fill(7, 1, 2)
      // ['a', 7, 'c']
      
    • entries(),keys() 和 values():
    • 遍历数组,返货iterator,可用for...of遍历或者next().value.
    ```
    // for...of
    for (let [index, elem] of ['a', 'b'].entries()) {
        console.log(index, elem);
      }
      // 0 "a"
      // 1 "b"
    //next()
    let letter = ['a', 'b', 'c'];
      let entries = letter.entries();
      console.log(entries.next().value); // [0, 'a']
      console.log(entries.next().value); // [1, 'b']
      console.log(entries.next().value); // [2, 'c']
    
    ```
    
    • includes(someData):是否包含某个值

      [1, 2, 3].includes(2)     // true
      [1, 2, 3].includes(4)     // false
      [1, 2, NaN].includes(NaN) // true
      
    • array.flat(),array.flatMap()

      • flat(Infinity)将多维数组拉平。Infinity:几层,Infinity:全部拉平。
      • flatMap(fun,this)只能展开一层数组:返回新的数组,不改变原数组。相当于执行Array.prototype.map()),然后对返回值组成的数组执行flat()方法
      // 相当于 [[2, 4], [3, 6], [4, 8]].flat()
      [2, 3, 4].flatMap((x) => [x, x * 2])
      // [2, 4, 3, 6, 4, 8]
      
      
    • 数组的空位

      • Array(3) // [, , ,]
  • 对象新增方法:Object.is();Object.assign();Object.getOwnPropertyDescriptors();__proto__属性.Object.setPrototypeOf(),Object.getPrototypeOf();Object.keys(),Object.values(),Object.entries();Object.fromEntries()

    • Object.is():判断两个值是否严格相等
    Object.is('foo', 'foo') // true
    Object.is({}, {}) // false
    
    • Object.assign():对象合并浅拷贝。
    • Object.getOwnPropertyDescriptors():解决了Object.assign()无法拷贝get和set属性问题。返回指定对象所有自身属性(非继承属性)的描述对象。
    const obj = {
      foo: 123,
      get bar() { return 'abc' }
    };
    Object.getOwnPropertyDescriptors(obj)
    
    • __proto__属性,Object.setPrototypeOf(),Object.getPrototypeOf()
    该属性没有写入 ES6 的正文,而是写入了附录,原因是__proto__前后的双下划线,说明它本质上是一个内部属性,而不是一个正式的对外的 API,只是由于浏览器广泛支持,才被加入了 ES6。标准明确规定,只有浏览器必须部署这个属性,其他运行环境不一定需要部署,而且新的代码最好认为这个属性是不存在的。因此,无论从语义的角度,还是从兼容性的角度,都不要使用这个属性,而是使用下面的Object.setPrototypeOf()(写操作)、Object.getPrototypeOf()(读操作)、Object.create()(生成操作)代替。
    
    • Object.keys(),Object.values(),Object.entries()
    • Object.fromEntries()
      • Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象。
      • 该方法的一个用处是配合URLSearchParams对象,将查询字符串转为对象。
      Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
      
      Object.fromEntries([
        ['foo', 'bar'],
        ['baz', 42]
      ])
      // { foo: "bar", baz: 42 }
      
      
  • Symbol

  • Set和Map

  • Proxy({target},{handler}):

    • 对象外访问的拦截:
    var proxy = new Proxy({}, {
          get: function(target, property) {
            return 35;
          }
        });
        
        proxy.time // 35
        proxy.name // 35
        proxy.title // 35
    
  • Reflect

    • Reflect对象和proxy差不多,的方法与Proxy对象的方法一一对应
    • Reflect.apply(target, thisArg, args)
    • Reflect.construct(target, args)
    • Reflect.get(target, name, receiver)
    • Reflect.set(target, name, value, receiver)
    • Reflect.defineProperty(target, name, desc)
    • Reflect.deleteProperty(target, name)
    • Reflect.has(target, name)
    • Reflect.ownKeys(target)
    • Reflect.isExtensible(target)
    • Reflect.preventExtensions(target)
    • Reflect.getOwnPropertyDescriptor(target, name)
    • Reflect.getPrototypeOf(target)
    • Reflect.setPrototypeOf(target, prototype)
  • Promise

    • 含义

    • Promise.prototype.then()

    • Promise.prototype.catch()

    • Promise.prototype.finally()

        promise
        .then(result => {···})
        .catch(error => {···})
        .finally(() => {···});
    
    • Promise.all([Promise1,Promise2,Promise3])
    • Promise.race([Promise1,Promise2,Promise3])
    • Promise.resolve(obj):将一个对象转化成promise对象
    Promise.resolve('foo')
    // 等价于
    new Promise(resolve => resolve('foo'))
    
    • Promise.reject():方法也会返回一个新的 Promise 实例,该实例的状态为rejected。
    const p = Promise.reject('出错了');
    // 等同于
    const p = new Promise((resolve, reject) => reject('出错了'))
    
    p.then(null, function (s) {
      console.log(s)
    });
    // 出错了
    
    
    • Promise.try():
    try {
      database.users.get({id: userId})
      .then(...)
      .catch(...)
    } catch (e) {
      // ...
    }
    等价于
    Promise.try(() => database.users.get({id: userId}))
      .then(...)
      .catch(...)
    
    
  • Generator

  • async

  • class

  • module:export default inmport

  • 装饰器类

    • 将一个函数加入class类中。
    @testable
    class MyTestableClass {
      // ...
    }
    
    function testable(target) {
      target.isTestable = true;
    }
    
    MyTestableClass.isTestable // true