您的位置:首頁 > 軟件教程 > 教程 > ES 2024 新特性

ES 2024 新特性

來源:好特整理 | 時間:2024-05-13 16:10:13 | 閱讀:108 |  標簽: 2 S   | 分享到:

ECMAScript 2024 新特性 ECMAScript 2024, the 15th edition, added facilities for resizing and transferring ArrayBuffers and SharedArrayBuffers; added a new

ECMAScript 2024 新特性

ECMAScript 2024, the 15th edition, added facilities for resizing and transferring ArrayBuffers and SharedArrayBuffers; added a new RegExp /v flag for creating RegExps with more advanced features for working with sets of strings; and introduced the Promise.withResolvers convenience method for constructing Promises, the Object.groupBy and Map.groupBy methods for aggregating data, the Atomics.waitAsync method for asynchronously waiting for a change to shared memory, and the String.prototype.isWellFormed and String.prototype.toWellFormed methods for checking and ensuring that strings contain only well-formed Unicode.

ECMAScript 2024,第 15 版,添加了用于調整 ArrayBuffer SharedArrayBuffer 大小和傳輸?shù)墓δ埽?添加了一個新的 RegExp /v 標志,用于創(chuàng)建具有更高級功能的 RegExp,用于處理字符串集; 并介紹了用于構造 Promise Promise.withResolvers 便捷方法、用于聚合數(shù)據(jù)的 Object.groupBy Map.groupBy 方法、用于異步等待共享內存更改的 Atomics.waitAsync 方法以及 String.prototype.isWellFormed String.prototype.toWellFormed 方法,用于檢查并確保字符串僅包含格式正確的 Unicode 。

一、 Promise.withResolvers ( )

This function returns an object with three properties: a new promise together with the resolve and reject functions associated with it.

該函數(shù)返回一個具有三個屬性的對象:一個新的 Promise 以及與其關聯(lián)的解決和拒絕函數(shù)。

1. 返回值

包含以下屬性的普通對象:

1.1. promise

一個 Promise 對象。

1.2. resolve

一個函數(shù),用于解決該 Promise 。

1.3. reject

一個函數(shù),用于拒絕該 Promise 。

2. 示例

Promise.withResolvers() 的使用場景是,當你有一個 promise ,需要通過無法包裝在 promise 執(zhí)行器內的某個事件監(jiān)聽器來解決或拒絕。

async function* readableToAsyncIterable(stream) {
  let { promise, resolve, reject } = Promise.withResolvers();
  stream.on("error", (error) => reject(error));
  stream.on("end", () => resolve());
  stream.on("readable", () => resolve());

  while (stream.readable) {
    await promise;
    let chunk;
    while ((chunk = stream.read())) {
      yield chunk;
    }
    ({ promise, resolve, reject } = Promise.withResolvers());
  }
}

3. 等價于

Promise.withResolvers() 完全等同于以下代碼:

let resolve, reject;
const promise = new Promise((res, rej) => {
  resolve = res;
  reject = rej;
});

使用 Promise.withResolvers() 關鍵的區(qū)別在于解決和拒絕函數(shù)現(xiàn)在與 Promise 本身處于同一作用域,而不是在執(zhí)行器中被創(chuàng)建和一次性使用。

4. 在非 Promise 構造函數(shù)上調用 withResolvers()

Promise.withResolvers() 是一個通用方法。它可以在任何實現(xiàn)了與 Promise() 構造函數(shù)相同簽名的構造函數(shù)上調用。

例如,我們可以在一個將 console.log 作為 resolve reject 函數(shù)傳入給 executor 的構造函數(shù)上調用它:

class NotPromise {
  constructor(executor) {
    // “resolve”和“reject”函數(shù)和原生的 promise 的行為完全不同
    // 但 Promise.withResolvers() 只是返回它們,就像是原生的 promise 一樣
    executor(
      (value) => console.log("以", value, "解決"),
      (reason) => console.log("以", reason, "拒絕"),
    );
  }
}
const { promise, resolve, reject } = Promise.withResolvers.call(NotPromise);
resolve("hello");

二、 Object.groupBy ( items, callbackfn )

callbackfn is called with two arguments: the value of the element and the index of the element.

The return value of groupBy is an object that does not inherit from %Object.prototype%.

callbackfn 是一個接受兩個參數(shù)的函數(shù)。 groupBy items 中的每個元素按升序調用一次 callbackfn ,并構造一個新對象。 Callbackfn 返回的每個值都被強制轉換為屬性鍵。 對于每個這樣的屬性鍵,結果對象都有一個屬性,其鍵是該屬性鍵,其值是一個數(shù)組,其中包含回調函數(shù)返回值強制為該鍵的所有元素。

使用兩個參數(shù)調用 callbackfn :元素的值和元素的索引。

groupBy 的返回值是一個不繼承自 Object.prototype 的對象。

1. 作用

Object.groupBy() 靜態(tài)方法根據(jù)提供的回調函數(shù)返回的字符串值對給定可迭代對象中的元素進行分組。返回的對象具有每個組的單獨屬性,其中包含組中的元素的數(shù)組。

2. 參數(shù)

2.1. items

一個將進行元素分組的可迭代對象(例如 Array )。

2.2. callbackFn

對可迭代對象中的每個元素執(zhí)行的函數(shù)。它應該返回一個值,可以被強制轉換成屬性鍵(字符串或 symbol ),用于指示當前元素所屬的分組。該函數(shù)被調用時將傳入以下參數(shù):

  • element :數(shù)組中當前正在處理的元素。
  • index :正在處理的元素在數(shù)組中的索引。

3. 返回值

一個帶有所有分組屬性的 null 原型對象,每個屬性都分配了一個包含相關組元素的數(shù)組。

4. 示例

4.1. 根據(jù) element 元素分組

Object.groupBy([
  { name: "蘆筍", type: "蔬菜", quantity: 5 },
  { name: "香蕉", type: "水果", quantity: 0 },
  { name: "山羊", type: "肉", quantity: 23 },
  { name: "櫻桃", type: "水果", quantity: 5 },
  { name: "魚", type: "肉", quantity: 22 },
], ({name}) => name)
// 輸出
/**
{
    "蔬菜": [
        {
            "name": "蘆筍",
            "type": "蔬菜",
            "quantity": 5
        }
    ],
    "水果": [
        {
            "name": "香蕉",
            "type": "水果",
            "quantity": 0
        },
        {
            "name": "櫻桃",
            "type": "水果",
            "quantity": 5
        }
    ],
    "肉": [
        {
            "name": "山羊",
            "type": "肉",
            "quantity": 23
        },
        {
            "name": "魚",
            "type": "肉",
            "quantity": 22
        }
    ]
}
*/

4.2. 自定義分組

const myCallback = ({ quantity }) => {
  return quantity > 5 ? "ok" : "restock";
}

const result = Object.groupBy([
  { name: "蘆筍", type: "蔬菜", quantity: 5 },
  { name: "香蕉", type: "水果", quantity: 0 },
  { name: "山羊", type: "肉", quantity: 23 },
  { name: "櫻桃", type: "水果", quantity: 5 },
  { name: "魚", type: "肉", quantity: 22 },
], myCallback);
// 輸出
/**
{
    "restock": [
        {
            "name": "蘆筍",
            "type": "蔬菜",
            "quantity": 5
        },
        {
            "name": "香蕉",
            "type": "水果",
            "quantity": 0
        },
        {
            "name": "櫻桃",
            "type": "水果",
            "quantity": 5
        }
    ],
    "ok": [
        {
            "name": "山羊",
            "type": "肉",
            "quantity": 23
        },
        {
            "name": "魚",
            "type": "肉",
            "quantity": 22
        }
    ]
}
*/

三、 Map.groupBy ( items, callbackfn )

callbackfn is called with two arguments: the value of the element and the index of the element.

The return value of groupBy is a Map.

callbackfn 是一個接受兩個參數(shù)的函數(shù)。 groupBy items 中的每個元素按升序調用一次回調函數(shù),并構造一個新的 Map 。 callbackfn 返回的每個值都用作 Map 中的鍵。 對于每個這樣的鍵,結果 Map 都有一個條目,其鍵是該鍵,其值是一個數(shù)組,其中包含 callbackfn 返回該鍵的所有元素。

使用兩個參數(shù)調用 callbackfn :元素的值和元素的索引。

groupBy 的返回值是一個 Map

1. 作用

Map.groupBy() 靜態(tài)方法使用提供的回調函數(shù)返回的值對給定可迭代對象中的元素進行分組。最終返回的 Map 使用測試函數(shù)返回的唯一值作為鍵,可用于獲取每個組中的元素組成的數(shù)組。

2. 參數(shù)

2.1. items

一個將進行元素分組的可迭代對象(例如 Array )。

2.2. callbackFn

對可迭代對象中的每個元素執(zhí)行的函數(shù)。它應該返回一個值(對象或原始類型)來表示當前元素的分組。該函數(shù)被調用時將傳入以下參數(shù):

  • element :數(shù)組中當前正在處理的元素。
  • index :正在處理的元素在數(shù)組中的索引。

3. 返回值

一個包含了每一個組的鍵的 Map 對象,每個鍵都分配了一個包含關聯(lián)組元素的數(shù)組。

4. 示例

const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy([
  { name: "蘆筍", type: "蔬菜", quantity: 9 },
  { name: "香蕉", type: "水果", quantity: 5 },
  { name: "山羊", type: "肉", quantity: 23 },
  { name: "櫻桃", type: "水果", quantity: 12 },
  { name: "魚", type: "肉", quantity: 22 },
], ({ quantity }) =>
  quantity < 6 ? restock : sufficient,
);
// 輸出 result Map
/**
new Map([
    [
        {
            "restock": false
        },
        [
            {
                "name": "蘆筍",
                "type": "蔬菜",
                "quantity": 9
            },
            {
                "name": "山羊",
                "type": "肉",
                "quantity": 23
            },
            {
                "name": "櫻桃",
                "type": "水果",
                "quantity": 12
            },
            {
                "name": "魚",
                "type": "肉",
                "quantity": 22
            }
        ]
    ],
    [
        {
            "restock": true
        },
        [
            {
                "name": "香蕉",
                "type": "水果",
                "quantity": 5
            }
        ]
    ]
])
*/

ES 2024 新特性

四、 Atomics.waitAsync ( typedArray, index, value, timeout )

This function returns a Promise that is resolved when the calling agent is notified or the the timeout is reached.

此函數(shù)返回一個 Promise ,當通知調用代理或達到超時時,該 Promise 會被解析。

1. 作用

Atomics.waitAsync() 靜態(tài)方法異步等待共享內存的特定位置并返回一個 Promise。

2. 參數(shù)

  • typedArray :基于 SharedArrayBuffer Int32Array BigInt64Array
  • index typedArray 中要等待的位置。
  • value :要測試的期望值。
  • timeout :可選 等待時間,以毫秒為單位。 NaN (以及會被轉換為 NaN 的值,例如 undefined )會被轉換為 Infinity 。負值會被轉換為 0。

3. 返回值

一個 Object ,包含以下屬性:

  • async :一個布爾值,指示 value 屬性是否為 Promise 。
  • value :如果 async false ,它將是一個內容為 " not-equal " 或 " timed-out " 的字符串(僅當 timeout 參數(shù)為 0 時)。如果 async true ,它將會是一個 Promise ,其兌現(xiàn)值為一個內容為 " ok " 或 " timed-out " 的字符串。這個 promise 永遠不會被拒絕。

4. 異常

  • TypeError :如果 typedArray 不是一個基于 SharedArrayBuffer Int32Array BigInt64Array ,則拋出該異常。
  • RangeError :如果 index 超出 typedArray 的范圍,則拋出該異常。

5. 示例

給定一個共享的 Int32Array 。

const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);

令一個讀取線程休眠并在位置 0 處等待,預期該位置的值為 0。 result.value 將是一個 promise 。

const result = Atomics.waitAsync(int32, 0, 0, 1000);
// { async: true, value: Promise {} }

在該讀取線程或另一個線程中,對內存位置 0 調用以令該 promise 為 " ok "。

Atomics.notify(int32, 0);
// { async: true, value: Promise {: 'ok'} }

如果它沒有為 " ok ",則共享內存該位置的值不符合預期( value 將是 " not-equal " 而不是一個 promise )或已經超時(該 promise 將為 " time-out ")。

五、 String.prototype.isWellFormed ( )

1. 作用

isWellFormed() 方法返回一個表示該字符串是否包含單獨代理項的布爾值。

1.1. 單獨代理項

單獨代理項(lone surrogate) 是指滿足以下描述之一的 16 位碼元:

  • 它在范圍 0xD800 到 0xDBFF 內(含)(即為前導代理),但它是字符串中的最后一個碼元,或者下一個碼元不是后尾代理。
  • 它在范圍 0xDC00 到 0xDFFF 內(含)(即為后尾代理),但它是字符串中的第一個碼元,或者前一個碼元不是前導代理。

2. 返回值

如果字符串不包含單獨代理項,返回 true ,否則返回 false

3. 示例

const strings = [
  // 單獨的前導代理
  "ab\uD800",
  "ab\uD800c",
  // 單獨的后尾代理
  "\uDFFFab",
  "c\uDFFFab",
  // 格式正確
  "abc",
  "ab\uD83D\uDE04c",
];

for (const str of strings) {
  console.log(str.isWellFormed());
}
// 輸出:
// false
// false
// false
// false
// true
// true

六、 String.prototype.toWellFormed ( )

1. 作用

toWellFormed() 方法返回一個字符串,其中該字符串的所有單獨代理項都被替換為 Unicode 替換字符 U+FFFD

2. 返回值

新的字符串是原字符串的一個拷貝,其中所有的單獨代理項被替換為 Unicode 替換字符 U+FFFD

3. 示例

const strings = [
  // 單獨的前導代理
  "ab\uD800",
  "ab\uD800c",
  // 單獨的后尾代理
  "\uDFFFab",
  "c\uDFFFab",
  // 格式正確
  "abc",
  "ab\uD83D\uDE04c",
];

for (const str of strings) {
  console.log(str.toWellFormed());
}
// Logs:
// "ab?"
// "ab?c"
// "?ab"
// "c?ab"
// "abc"
// "ab?c"

七、RegExp /v

1. 作用

/v 解鎖了對擴展字符類的支持,包括以下功能:

  • 字符串的 Unicode 屬性
  • 集合表示法+字符串文字語法
  • 改進的不區(qū)分大小寫的匹配

2. 示例

2.1. 基礎示例

const re = /…/v;

2.2. Unicode

const re = /^\p{RGI_Emoji}$/v;
re.test('?'); // '\u26BD'
// → true ?
re.test('?????'); // '\u{1F468}\u{1F3FE}\u200D\u2695\uFE0F'
// → true ?

v 標志支持字符串的以下 Unicode 屬性:

  • Basic_Emoji
  • Emoji_Keycap_Sequence
  • RGI_Emoji_Modifier_Sequence
  • RGI_Emoji_Flag_Sequence
  • RGI_Emoji_Tag_Sequence
  • RGI_Emoji_ZWJ_Sequence
  • RGI_Emoji

隨著 Unicode 標準定義了字符串的其他屬性,受支持的屬性列表將來可能會增加。

2.3. 結合 --

/[\p{Script_Extensions=Greek}--π]/v.test('π'); // → false
/[\p{Script_Extensions=Greek}--[αβγ]]/v.test('α'); // → false
/[\p{Script_Extensions=Greek}--[α-γ]]/v.test('β'); // → false
/[\p{Decimal_Number}--[0-9]]/v.test('?'); // → true
/[\p{Decimal_Number}--[0-9]]/v.test('4'); // → false
/^\p{RGI_Emoji_Tag_Sequence}$/v.test('???????'); // → true
/^[\p{RGI_Emoji_Tag_Sequence}--\q{???????}]$/v.test('???????'); // → false

2.4. 結合 &&

const re = /[\p{Script_Extensions=Greek}&&\p{Letter}]/v;
re.test('π'); // → true
re.test('?'); // → false

const re2 = /[\p{White_Space}&&\p{ASCII}]/v;
re2.test('\n'); // → true
re2.test('\u2028'); // → false

3. V 標志與 U 標志有何不同

  1. 使用新語法的無效模式現(xiàn)在變得有效
  2. 一些以前有效的模式現(xiàn)在是錯誤的,特別是那些字符類包含未轉義特殊字符 ( ) [ { } / - | 的模式或雙標點符號
  3. u 標志存在令人困惑的不區(qū)分大小寫的匹配行為。 v 標志具有不同的、改進的語義

引用

  • 【 ecma262 】
  • 【 MDN 】
小編推薦閱讀

好特網發(fā)布此文僅為傳遞信息,不代表好特網認同期限觀點或證實其描述。

相關視頻攻略

更多

掃二維碼進入好特網手機版本!

掃二維碼進入好特網微信公眾號!

本站所有軟件,都由網友上傳,如有侵犯你的版權,請發(fā)郵件[email protected]

湘ICP備2022002427號-10 湘公網安備:43070202000427號© 2013~2024 haote.com 好特網