ES2021 我學不動了,此次只學這 3 個。

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

1.邏輯賦值操做符

你有遇到過這樣的狀況嗎?git

function example(a) {
  // Default `a` to "foo"
  if (!a) {
    a = "foo";
  }
  // or
  a = a || "foo";
}

某些初始化的時候須要一些冗長的邏輯代碼github

function example(opts) {
  // Ok, but could trigger setter.
  opts.foo = opts.foo ?? "bar";

  // No setter, but 'feels wrong' to write.
  opts.baz ?? (opts.baz = "qux");
}

example({ foo: "foo" });

在這裏插入圖片描述
在這裏插入圖片描述

function example(opts) {
  // 舊的方式
  if (!a) {
    a = "foo";
  }
  // or
  a = a || "foo";
  // 新的方式
  a ||= "foo"
}

example({ foo: "foo" });
function example(opts) {
  // 舊的方式
  opts.foo = opts.foo ?? "bar";
  // 新的方式
  opts.foo ??= "bar";

  // 舊的方式
  opts.baz ?? (opts.baz = "qux");
  // 新的方式
  opts.baz ??= "qux";
}

example({ foo: "foo" });

在這裏插入圖片描述
1605350041175
在這裏插入圖片描述

a = a + b;
a += b;
a = a - b;
a -= b;

在這裏插入圖片描述

2.Promise.any

Promise.any。 從字面意思來看,相信聰明的你應該能大體猜出這個 API 的做用。Promise.any 接受一個 Promise 的數組。當其中任何一個 Promise 完成(fullfill)時,就返回那個已經有完成值的 Promise。若是全部的 Promise 都拒絕(reject),則返回一個拒絕的 Promise,該 Promise 的返回值是一個 AggregateError 對象。chrome

Promise.any(promises).then(
  (first) => {
    // 任意一個Promise完成了
  },
  (error) => {
    // 全部Promise都被拒絕了
  }
);

在這裏插入圖片描述

Promise.any([
  fetch("https://v8.dev/").then(() => "home"),
  fetch("https://v8.dev/blog").then(() => "blog"),
  fetch("https://v8.dev/docs").then(() => "docs"),
])
  .then((first) => {
    // Any of the promises was fulfilled.
    console.log(first);
    // → 'home'
  })
  .catch((error) => {
    // All of the promises were rejected.
    console.log(error);
  });

例如一些播放平臺,能夠經過這個來測試當前延遲最低的線路是哪一個,優先切換到對應的最快的線路。
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
來,亮出祖傳降級代碼數組

function reverse(promise) {
  return new Promise((resolve, reject) =>
    Promise.resolve(promise).then(reject, resolve)
  );
}
function promiseAny(iterable) {
  return reverse(Promise.all([...iterable].map(reverse)));
}
// https://github.com/m0ppers/promise-any/blob/master/index.js

實現很簡單,經過一個反轉函數,利用 Promisea.all 的特性,只要一個 Promise 被拒絕了,就進入到 reject,所以反轉 resolvereject 就能模擬出 Promise.any 了。
在這裏插入圖片描述
1605350041175在這裏插入圖片描述promise

3.數字分隔符

let fee = 1000000000;
let fee = 1_000_000_000;

這個模式不只在十進制能夠用,二進制,十六進制....甚至 BigInt,均可以使用。babel

// Binary Literals
let nibbles = 0b1010_0001_1000_0101;
// Hex Literal
let message = 0xa0_b0_c0;
// BigInt Literal
const max = 2n ** (64n - 1n) - 1n;
console.log(max === 9_223_372_036_854_775_807n);

以上特性均在最新版 chrome 支持,快打開控制檯玩耍吧。函數

若是想要在實際項目中使用,請使用如下兩個插件。測試

最後

image

相關文章
相關標籤/搜索