复习ES(6-11)语法之ES11

目录

String.prototype.matchAll()

const str = `
<html>
    <body>
        <div>这是第一个div</div>
        <p>我是p</p>
        <div>这是第二个div</div>
        <span>我是span</span>
    </body>
</html>
`;
function selectDiv(regExp, str) {
  let matches = [];
  while (true) {
    const match = regExp.exec(str);
    if (match == null) {
      break;
    }
    matches.push(match[1]);
  }
  return matches;
}
const regExp = /<div>(.*)<\/div>/g;
const res = selectDiv(regExp, str); 
console.log(res);// [ '这是第一个div', '这是第二个div' ]

ES2020 增加了String.prototype.matchAll()方法,可以一次性取出所有匹配。不过,它返回的是一个遍历器(Iterator),而不是数组。

const regExp = /<div>(.*)<\/div>/g;
// const res = selectDiv(regExp, str);
// console.log(res);// [ '这是第一个div', '这是第二个div' ]
function selectDiv(regExp, str) {
  let matches = [];
  for (let match of str.matchAll(regExp)) {
    matches.push(match[1]);
  }
  return matches;
}
const res = selectDiv(regExp, str);
console.log(res); // [ '这是第一个div', '这是第二个div' ]

按需导入

前端应用初始化时根本不需要全量加载逻辑资源,为了首屏渲染速度更快,很多时候都是按需加载,比如懒加载图片等。而这些按需执行逻辑资源都体现在某一个事件回调中去加载。

const oBtn = document.querySelector("#btn");
oBtn.addEventListener("click", () => {
  import("./ajax").then((mod) => {
    mod.default("static/a.json", (res) => {
      console.log(res);
    });
  });
});

新的原始数据类型:BigInt

BigInt数据类型的目的是比Number数据类型支持的范围更大的整数值。

要创建BigInt,只需在整数的末尾追加n即可。

const max = 2 ** 53;
console.log(max);
console.log(Number.MAX_SAFE_INTEGER);
console.log(max === max + 1); // true

const bigInt = 9007199254740993n;
console.log(bigInt);
console.log(typeof bigInt); // bigint

console.log(1n == 1); // true
console.log(1n === 1); // false 类型不同

const bigInt2 = BigInt(9007199254740993n);
console.log(bigInt == bigInt2); // true
console.log(bigInt === bigInt2); // true

Promise扩展

Promise.all()方法只适合所有异步操作都成功的情况,如果有一个操作失败,就无法满足要求。

Promise.all([
  Promise.resolve({
    code: 200,
    data: [1, 2, 3],
  }),
  Promise.reject({
    code: 500,
    data: [],
  }),
  Promise.resolve({
    code: 200,
    data: [7, 8, 9],
  }),
])
  .then((res) => {
    console.log(res);
    console.log("成功");
  })
  .catch((err) => {
    console.log(err);
    console.log("失败");
  });

Promise.all()可以确定所有请求都成功了,但是只要有一个请求失败,它就会报错,而不管另外的请求是否结束。

为了解决这个问题,ES2020 引入了Promise.allSettled()方法,用来确定一组异步操作是否都结束了(不管成功或失败)。所以,它的名字叫做”Settled“,包含了”fulfilled“和”rejected“两种情况。

Promise.allSettled([
  Promise.resolve({
    code: 200,
    data: [1, 2, 3],
  }),
  Promise.reject({
    code: 500,
    data: [],
  }),
  Promise.resolve({
    code: 200,
    data: [7, 8, 9],
  }),
])
  .then((res) => {
    console.log(res);
    const data = res.filter((item) => item.status === "fulfilled");
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
    console.log("失败");
  });

// [
//   { status: 'fulfilled', value: { code: 200, data: [Array] } },
//   { status: 'rejected', reason: { code: 500, data: [] } },
//   { status: 'fulfilled', value: { code: 200, data: [Array] } }
// ]

globalThis

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

在不同环境下全局对象不一样。例如:node⇒global,web⇒window/self

const getGlobal = () => {
  if (typeof self !== "undefined") {
    return self;
  }
  if (typeof window !== "undefined") {
    return window;
  }
  if (typeof global !== "undefined") {
    return global;
  }
  throw new Error("无法找到全局对象");
};
const _global = getGlobal();
console.log(_global);

console.log(globalThis);

可选链

可选链?. 是一种以安全的方式去访问嵌套的对象属性,即使某个属性根本就不存在。

可选链?. 能够使代码变得简便,当位于 ?. 前面的值为 undefinednull 时,会立即阻止代码的执行,并返回 undefined。

const user = {
  address: {
    street: "xx街道",
    getNum() {
      return "80号";
    },
  },
};
const street1 = user && user.address && user.address.street;
const street2 = user?.address?.street;
const num = user?.address?.getNum?.();
console.log(street1);
console.log(street2);
console.log(num);

空值合并运算符

为变量分配默认值时,通常使用逻辑或运算符 ||

let count;
let result = count || 1 ;
console.log(result); // 1

有些时候,如果将空字符串视为有效值,使用逻辑或运算符 || 并不会得到想要的结果。例如:当b为0或者false时,视为有效值,但是a的值却是5

const b = 0;
const a = b || 5;
console.log(a); // 5

空值合并运算符可以解决这种情况。当第一个值是null 或者 undefined 时,它只返回第二个值。

const b = 0;
// const a = b || 5;
// console.log(a); // 5
const a = b ?? 5;
console.log(a); // 0
posted @ 2023-07-10 21:34  小风车吱呀转  阅读(7)  评论(0编辑  收藏  举报