ES7 – 11新特性总结

es7

  1 Array.prototype.includes  之前都是使用indexOf判断,没有返回-1,现在includes更加方便

    Includes  方法用来检测数组中是否包含某个元素,返回boolean值

    let arr = [1, 2, 3, 4, 5];

    arr.includes(1);// true

    arr.includes(6);// false

  2 指数操作符 **,用来实现幂运算,功能与 Math.pow 结果相同

    2 ** 10;// 2 的 10 次方,与 Math.pow(2, 10); 结果相同,都是 1024

es8

  async 和 await  这两种语法结合,可以让异步代码像同步代码一样

    async 是 异步 的简写,await 可以认为是 async wait 的简写,await 理解为等待一个异步方法执行完成

   1 async 函数的返回值为 promise 对象

    promise 对象的结果是由 async 函数执行的返回值决定

    // 方法前面加上一个 async ,就变成了一个async函数了,
    // 只要返回值不是一个promise对象,返回值就是一个成功的promise对象,参考promise
    // 返回的是一个promise对象,该promise返回成功,则async函数返回成功,该promise返回失败,则async返回失败
    async function fn(){
      // return '晚上要学习';
      return new Promise((resolve, reject)=>{
        resolve('成功');
        // reject('失败');
      })
    }
    const result = fn();
    console.log(result);// 可以看到返回值是要给promise对象
    result.then(value =>{
      console.log('返回成功');
    }, reason =>{
      console.log('返回失败');
    })

   2 await 表达式

    await 必须写在 async 函数中

 

    await 右侧的表达式一般为 promise 对象

    await 返回的是 promise 成功的值

    await 的 promise 失败了,就会抛出异常,需要通过 try…catch 捕获处理

    // 创建一个 promise 对象
    const p = new Promise((resolve, reject) =>{
      // resolve('成功');
      reject('失败');
    })
    // await 要放在 async 中
    async function fn(){
      try{
        let result = await p;// await 返回结果就是 promise 对象返回成功的值
        console.log(result);// 成功
      } catch (e) {// 在 catch 中可以获取promise对象状态为失败的值
        console.log(e);// 失败
      }
    }
    fn();// 调用函数

   3 async 和 await 结合 在 vue 中结合 axios 使用(异步请求同步化

    1. 在不同情况下发送请求,做相同的处理

    export default{
      name: 'test',
      data(){
        return {
          tableData: []
        }
      },
      created() {
        this.getTableData();
      },
      methods: {
        handleSearch(){// 在create 中的请求结果和在这个方法中的处理结果相同
          this.getTableData();
        },
        async getTableData(){
          try {
            let res = await axios.get(url)
            this.tableData = res.data;
          } catch (err) {
            console.log('请求出错');
          }
        }
      }
    }

    2.在不容情况下的请求,做不同的处理

    export default{
      name: 'test',
      data(){
        return {
          tableData: []
        }
      },
      async created() {
        try{
          let res = await this.getTableData();
          this.tableData = res.data;
        }catch(err){
          console.log('请求出错');
        }
      },
      methods: {
        async handleSearch(){
          try {
            let res = await this.getTableData();
            this.tableData = res.data;
          } catch(err) {
            console.log('请求出错');
          }
          this.getTableData();
        },
        getTableData(){
          return new Promise((resolve, reject) =>{
            axios.get(url);
          }).then(res=>{
            resolve(res);
          }).catch(err=>{
            reject(err);
          })
        }
      }
    }

  对象方法的扩展

    Object.values()  返回一个给定对象的所有可枚举属性值的数组

    Object.entries()  返回一个给定对象自身可遍历属性 [key, value] 的数组

    Object.getOwnPropertyDescriptors()  返回指定对象所有自身属性的描述对象

    const p = {
      LPL: '我们是冠军',
      RNG: ['UZI', 'Letme', 'xiaohu', 'MLXG', 'Ming']
    }
    Object.keys(p);// ['LPL','RNG'] 返回key数组
    Object.values(p);// ['我们是冠军', ['UZI', 'Letme', 'xiaohu', 'MLXG', 'Ming']]  返回值对应的数组
    Object.entries(p);// [['LPL', '我们是冠军'],['RNG', ['UZI', 'Letme', 'xiaohu', 'MLXG', 'Ming']]]  返回值是一个数组,每个元素也都是一个数组
    Object.getOwnPropertyDescriptors(p);// 返回结果是对象,对象中还是对象,还有别的值,打印看一下

 es9

  扩展运算符与 rest 参数

    rest 参数与扩展运算符在 es6 中已经引入了,不过 es6 中只是针对数组,对象不行

    在 es9 中为对象提供了像数组一样的 rest 参数和扩展运算符,注意rest参数后面不允许有其他参数

// 使用 rest 参数操作对象,user 是后面没有声明的对象, 注意rest参数后面不能有其他参数
function connect({ RNG, adc, ...user }) {
  console.log(RNG);// 全华班
  console.log(adc);// UZI
  console.log(user);// {UZI: '简自豪', MLXG: '刘世宇'}
}
connect({
  RNG: '全华班',
  adc: 'UZI',
  UZI: '简自豪',
  MLXG: '刘世宇'
})
const ONE = { q: '天音波' }, TEO = { w: '金钟罩' }, THREE = { e: '天雷破' }, FOUR = { r: '猛龙摆尾' };
const MLXG = { ...ONE, ...TEO, ...THREE, ...FOUR };
console.log(MLXG);// {q: "天音波", w: "金钟罩", e: "天雷破", r: "猛龙摆尾"}

   

es10

  对象的扩展方法Object.fromEntries()  参数是一个二维数组,或者是一个 Map

const rng = Object.fromEntries([['adc', 'UZI'], ['uzi', '简自豪']]);// 这里是二维数组,数组里面套数组
console.log(rng);// {adc: "UZI", uzi: "简自豪"}

const map = new Map();
map.set('adc', 'uzi');
const uzi = Object.fromEntries(map);// 这里是 map 集合,这里查看es8中的Object.entries()方法
console.log(uzi);// {adc: "uzi"}

  字符串方法扩展 trimStart 和 trimEnd

    trim 是清空字符串两端空格,trimStart 则是清除开始空格,trimEnd 清除结束空格

  数组方法扩展 flat 与 flatMap

    flat 将数组维度降低,多维数组转换成低维数组

const arr = [1, 2, 5, [6, 7, [8, 9]]];
// 参数是一个数字,表示深度,三维数组变成一维数组,深度为2
console.log(arr.flat(2));// [1, 2, 5, 6, 7, 8, 9]
console.log(arr.flat());// [1, 2, 5, 6, 7, [8, 9]]

const arr1 = [1, 2, 3];
const result = arr1.map(i => i * 10);// [10, 20, 30]
const result1 = arr1.map(i => i * 10);// [[10], [20], [30]]
const result11 = arr1.flatMap(i => i * 10);// [10, 20, 30] // 只是这一个功能,降低数组维度

   Symbol 扩展 

   Symbol.prototype.description

let zn = Symbol('张宁');
console.log(zn.description);// 输出字符串 张宁

 

es11

  私有属性,声明的标志是一个#

    class Persion{
            // 公有属性
            name;
            // 私有属性,#为私有属性的标志
            #age;
            #weight;
            constructor(name, age, weight){
                this.name = name;
                this.#age = age;
                this.#weight = weight;
            }
            // 类里面的方法
            say(){
                console.log(this.name);
                console.log(this.#age);
                console.log(this.#weight);
            }
        }
        const boy = new Persion('张宁', 24, '80kg');
        console.log(boy);// Persion {name: "张宁", #age: 24, #weight: "80kg"}
        console.log(boy.name);// 张宁
        console.log(boy.#age);// Private field '#age' must be declared in an enclosing class
        console.log(boy.#weight);// 提示私有属性,只能出现在类里面
        boy.say();// 依次输出 张宁 24 80kg

   Promist.allSettled() 方法

// 声明两个promise对象
const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功1');
    // reject('失败1');
  }, 1000)
});
const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    // resolve('成功2');
    reject('失败2');
  }, 1000)
});

// 两个都成功才会返回成功, 返回数据一个是状态 resolve,
// 一个是值,存在数组中 [{status: "fulfilled", value: "成功1"},{status: "fulfilled", value: "成功2"}],fulfilled表示成功
// 当p2返回错误的时候,result依然返回成功,Promise.allSettled 总是返回成功,
// 当p2返回错误的时候,返回数据一个是状态 resolve,
// 一个是值 [{status: "fulfilled", value: "成功1"},{status: "rejected"reason: "失败2"]
const result = Promise.allSettled([p1, p2]);
// 两个都成功才会返回成功, 返回数据一个是状态 resolve,一个是值在数组中 ['成功1', '成功2']
// 有一个返回失败,就是失败,返回数据一个是状态 rejected,一个是错误的值 失败1
const res = Promise.all([p1, p2]);
console.log(result);
console.log(res);

   字符串扩展  String.prototype.matchAll()

    通过正则表达式获取想要得到的字段

  可选链操作符  ?.  判断?前面的值有没有传入,如果传递了,就去读取后面的属性,没有传递就返回 undefined

function main(config) {
  // 当main传递数据的时候,返回 uzi
  console.log(config.rng.adc);
}
main({rng:{adc: 'uzi'}});// main 中传递数据的时候返回 uzi
main();// 什么都不传递的时候报错 Cannot read property 'rng' of undefined

function main1(config) { console.log(config?.rng?.adc); } main1({rng:{adc: 'uzi'}});// main 中传递数据的时候返回 uzi main1();// 什么都不传递的时候,返回undefined

   动态 import  就是按需加载,懒加载

  BigInt 类型

// BigInt 类型  大整型
let n = 510n;
console.log(n, typeof(n));// 510n bigint

let nn = 123;
console.log(BigInt(nn));// 输出 123n  BigInt函数中只能是整数,不能是浮点类型的数

// 大整型主要应用于大数值的运算
let max = Number.MAX_SAFE_INTEGER;// 最大整数
console.log(max);// 9007199254740991
console.log(max + 1);// 9007199254740992
console.log(max + 1);// 9007199254740992  已经不能加上去了
// 可以通过大整型进行计算相加,大整型不能直接与int进行计算,都是大整型才能进行计算
console.log(BigInt(max));// 9007199254740991n
console.log(BigInt(max) + BigInt(1));// 9007199254740992n
console.log(BigInt(max) + BigInt(6));// 9007199254740997n

  绝对全局对象 globalThis

    之前在javascript在不同环境获取全局对象有不同的方式

      node 中 通过 global 

      web 中通过 window,self

    现在 globalThis 提供了一个标准的方式来获取不同环境下的全局 this 对象。

    不像 window 或者 self 这些属性,它确保可以在有无窗口的各种环境下正常工作。

    所以,可以放心使用 globalThis,不用担心它的运行环境。全局作用域中的 this 就是globalThis

 

Tags: