经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
ES 2024 新特性
来源:cnblogs  作者:日升_rs  时间:2024/5/13 14:12:28  对本文有异议

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 版,添加了用于调整 ArrayBufferSharedArrayBuffer 大小和传输的功能; 添加了一个新的 RegExp /v 标志,用于创建具有更高级功能的 RegExp,用于处理字符串集; 并介绍了用于构造 PromisePromise.withResolvers 便捷方法、用于聚合数据的 Object.groupByMap.groupBy 方法、用于异步等待共享内存更改的 Atomics.waitAsync 方法以及 String.prototype.isWellFormedString.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.

该函数返回一个具有三个属性的对象:一个新的 Promise 以及与其关联的解决和拒绝函数。

1. 返回值

包含以下属性的普通对象:

1.1. promise

一个 Promise 对象。

1.2. resolve

一个函数,用于解决该 Promise

1.3. reject

一个函数,用于拒绝该 Promise

2. 示例

Promise.withResolvers() 的使用场景是,当你有一个 promise,需要通过无法包装在 promise 执行器内的某个事件监听器来解决或拒绝。

  1. async function* readableToAsyncIterable(stream) {
  2. let { promise, resolve, reject } = Promise.withResolvers();
  3. stream.on("error", (error) => reject(error));
  4. stream.on("end", () => resolve());
  5. stream.on("readable", () => resolve());
  6. while (stream.readable) {
  7. await promise;
  8. let chunk;
  9. while ((chunk = stream.read())) {
  10. yield chunk;
  11. }
  12. ({ promise, resolve, reject } = Promise.withResolvers());
  13. }
  14. }

3. 等价于

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

  1. let resolve, reject;
  2. const promise = new Promise((res, rej) => {
  3. resolve = res;
  4. reject = rej;
  5. });

使用 Promise.withResolvers() 关键的区别在于解决和拒绝函数现在与 Promise 本身处于同一作用域,而不是在执行器中被创建和一次性使用。

4. 在非 Promise 构造函数上调用 withResolvers()

Promise.withResolvers() 是一个通用方法。它可以在任何实现了与 Promise() 构造函数相同签名的构造函数上调用。

例如,我们可以在一个将 console.log 作为 resolvereject 函数传入给 executor 的构造函数上调用它:

  1. class NotPromise {
  2. constructor(executor) {
  3. // “resolve”和“reject”函数和原生的 promise 的行为完全不同
  4. // 但 Promise.withResolvers() 只是返回它们,就像是原生的 promise 一样
  5. executor(
  6. (value) => console.log("以", value, "解决"),
  7. (reason) => console.log("以", reason, "拒绝"),
  8. );
  9. }
  10. }
  11. const { promise, resolve, reject } = Promise.withResolvers.call(NotPromise);
  12. 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 是一个接受两个参数的函数。 groupByitems 中的每个元素按升序调用一次 callbackfn,并构造一个新对象。 Callbackfn 返回的每个值都被强制转换为属性键。 对于每个这样的属性键,结果对象都有一个属性,其键是该属性键,其值是一个数组,其中包含回调函数返回值强制为该键的所有元素。

使用两个参数调用 callbackfn:元素的值和元素的索引。

groupBy 的返回值是一个不继承自 Object.prototype 的对象。

1. 作用

Object.groupBy() 静态方法根据提供的回调函数返回的字符串值对给定可迭代对象中的元素进行分组。返回的对象具有每个组的单独属性,其中包含组中的元素的数组。

2. 参数

2.1. items

一个将进行元素分组的可迭代对象(例如 Array)。

2.2. callbackFn

对可迭代对象中的每个元素执行的函数。它应该返回一个值,可以被强制转换成属性键(字符串或 symbol),用于指示当前元素所属的分组。该函数被调用时将传入以下参数:

  • element:数组中当前正在处理的元素。
  • index:正在处理的元素在数组中的索引。

3. 返回值

一个带有所有分组属性的 null 原型对象,每个属性都分配了一个包含相关组元素的数组。

4. 示例

4.1. 根据 element 元素分组

  1. Object.groupBy([
  2. { name: "芦笋", type: "蔬菜", quantity: 5 },
  3. { name: "香蕉", type: "水果", quantity: 0 },
  4. { name: "山羊", type: "肉", quantity: 23 },
  5. { name: "樱桃", type: "水果", quantity: 5 },
  6. { name: "鱼", type: "肉", quantity: 22 },
  7. ], ({name}) => name)
  8. // 输出
  9. /**
  10. {
  11. "蔬菜": [
  12. {
  13. "name": "芦笋",
  14. "type": "蔬菜",
  15. "quantity": 5
  16. }
  17. ],
  18. "水果": [
  19. {
  20. "name": "香蕉",
  21. "type": "水果",
  22. "quantity": 0
  23. },
  24. {
  25. "name": "樱桃",
  26. "type": "水果",
  27. "quantity": 5
  28. }
  29. ],
  30. "肉": [
  31. {
  32. "name": "山羊",
  33. "type": "肉",
  34. "quantity": 23
  35. },
  36. {
  37. "name": "鱼",
  38. "type": "肉",
  39. "quantity": 22
  40. }
  41. ]
  42. }
  43. */

4.2. 自定义分组

  1. const myCallback = ({ quantity }) => {
  2. return quantity > 5 ? "ok" : "restock";
  3. }
  4. const result = Object.groupBy([
  5. { name: "芦笋", type: "蔬菜", quantity: 5 },
  6. { name: "香蕉", type: "水果", quantity: 0 },
  7. { name: "山羊", type: "肉", quantity: 23 },
  8. { name: "樱桃", type: "水果", quantity: 5 },
  9. { name: "鱼", type: "肉", quantity: 22 },
  10. ], myCallback);
  11. // 输出
  12. /**
  13. {
  14. "restock": [
  15. {
  16. "name": "芦笋",
  17. "type": "蔬菜",
  18. "quantity": 5
  19. },
  20. {
  21. "name": "香蕉",
  22. "type": "水果",
  23. "quantity": 0
  24. },
  25. {
  26. "name": "樱桃",
  27. "type": "水果",
  28. "quantity": 5
  29. }
  30. ],
  31. "ok": [
  32. {
  33. "name": "山羊",
  34. "type": "肉",
  35. "quantity": 23
  36. },
  37. {
  38. "name": "鱼",
  39. "type": "肉",
  40. "quantity": 22
  41. }
  42. ]
  43. }
  44. */

三、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 是一个接受两个参数的函数。 groupByitems 中的每个元素按升序调用一次回调函数,并构造一个新的 Mapcallbackfn 返回的每个值都用作 Map 中的键。 对于每个这样的键,结果 Map 都有一个条目,其键是该键,其值是一个数组,其中包含 callbackfn 返回该键的所有元素。

使用两个参数调用 callbackfn:元素的值和元素的索引。

groupBy 的返回值是一个 Map

1. 作用

Map.groupBy() 静态方法使用提供的回调函数返回的值对给定可迭代对象中的元素进行分组。最终返回的 Map 使用测试函数返回的唯一值作为键,可用于获取每个组中的元素组成的数组。

2. 参数

2.1. items

一个将进行元素分组的可迭代对象(例如 Array)。

2.2. callbackFn

对可迭代对象中的每个元素执行的函数。它应该返回一个值(对象或原始类型)来表示当前元素的分组。该函数被调用时将传入以下参数:

  • element:数组中当前正在处理的元素。
  • index:正在处理的元素在数组中的索引。

3. 返回值

一个包含了每一个组的键的 Map 对象,每个键都分配了一个包含关联组元素的数组。

4. 示例

  1. const restock = { restock: true };
  2. const sufficient = { restock: false };
  3. const result = Map.groupBy([
  4. { name: "芦笋", type: "蔬菜", quantity: 9 },
  5. { name: "香蕉", type: "水果", quantity: 5 },
  6. { name: "山羊", type: "肉", quantity: 23 },
  7. { name: "樱桃", type: "水果", quantity: 12 },
  8. { name: "鱼", type: "肉", quantity: 22 },
  9. ], ({ quantity }) =>
  10. quantity < 6 ? restock : sufficient,
  11. );
  12. // 输出 result Map
  13. /**
  14. new Map([
  15. [
  16. {
  17. "restock": false
  18. },
  19. [
  20. {
  21. "name": "芦笋",
  22. "type": "蔬菜",
  23. "quantity": 9
  24. },
  25. {
  26. "name": "山羊",
  27. "type": "肉",
  28. "quantity": 23
  29. },
  30. {
  31. "name": "樱桃",
  32. "type": "水果",
  33. "quantity": 12
  34. },
  35. {
  36. "name": "鱼",
  37. "type": "肉",
  38. "quantity": 22
  39. }
  40. ]
  41. ],
  42. [
  43. {
  44. "restock": true
  45. },
  46. [
  47. {
  48. "name": "香蕉",
  49. "type": "水果",
  50. "quantity": 5
  51. }
  52. ]
  53. ]
  54. ])
  55. */

image

四、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.

此函数返回一个 Promise,当通知调用代理或达到超时时,该 Promise 会被解析。

1. 作用

Atomics.waitAsync() 静态方法异步等待共享内存的特定位置并返回一个 Promise。

2. 参数

  • typedArray:基于 SharedArrayBufferInt32ArrayBigInt64Array
  • indextypedArray 中要等待的位置。
  • value:要测试的期望值。
  • timeout:可选 等待时间,以毫秒为单位。NaN(以及会被转换为 NaN 的值,例如 undefined)会被转换为 Infinity。负值会被转换为 0。

3. 返回值

一个 Object,包含以下属性:

  • async:一个布尔值,指示 value 属性是否为 Promise
  • value:如果 asyncfalse,它将是一个内容为 "not-equal" 或 "timed-out" 的字符串(仅当 timeout 参数为 0 时)。如果 asynctrue,它将会是一个 Promise,其兑现值为一个内容为 "ok" 或 "timed-out" 的字符串。这个 promise 永远不会被拒绝。

4. 异常

  • TypeError:如果 typedArray 不是一个基于 SharedArrayBufferInt32ArrayBigInt64Array,则抛出该异常。
  • RangeError:如果 index 超出 typedArray 的范围,则抛出该异常。

5. 示例

给定一个共享的 Int32Array

  1. const sab = new SharedArrayBuffer(1024);
  2. const int32 = new Int32Array(sab);

令一个读取线程休眠并在位置 0 处等待,预期该位置的值为 0。result.value 将是一个 promise

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

在该读取线程或另一个线程中,对内存位置 0 调用以令该 promise 为 "ok"。

  1. Atomics.notify(int32, 0);
  2. // { async: true, value: Promise {<fulfilled>: '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. 示例

  1. const strings = [
  2. // 单独的前导代理
  3. "ab\uD800",
  4. "ab\uD800c",
  5. // 单独的后尾代理
  6. "\uDFFFab",
  7. "c\uDFFFab",
  8. // 格式正确
  9. "abc",
  10. "ab\uD83D\uDE04c",
  11. ];
  12. for (const str of strings) {
  13. console.log(str.isWellFormed());
  14. }
  15. // 输出:
  16. // false
  17. // false
  18. // false
  19. // false
  20. // true
  21. // true

六、String.prototype.toWellFormed ( )

1. 作用

toWellFormed() 方法返回一个字符串,其中该字符串的所有单独代理项都被替换为 Unicode 替换字符 U+FFFD

2. 返回值

新的字符串是原字符串的一个拷贝,其中所有的单独代理项被替换为 Unicode 替换字符 U+FFFD

3. 示例

  1. const strings = [
  2. // 单独的前导代理
  3. "ab\uD800",
  4. "ab\uD800c",
  5. // 单独的后尾代理
  6. "\uDFFFab",
  7. "c\uDFFFab",
  8. // 格式正确
  9. "abc",
  10. "ab\uD83D\uDE04c",
  11. ];
  12. for (const str of strings) {
  13. console.log(str.toWellFormed());
  14. }
  15. // Logs:
  16. // "ab?"
  17. // "ab?c"
  18. // "?ab"
  19. // "c?ab"
  20. // "abc"
  21. // "ab??c"

七、RegExp /v

1. 作用

/v 解锁了对扩展字符类的支持,包括以下功能:

2. 示例

2.1. 基础示例

  1. const re = /…/v;

2.2. Unicode

  1. const re = /^\p{RGI_Emoji}$/v;
  2. re.test('?'); // '\u26BD'
  3. // → true ?
  4. re.test('???????'); // '\u{1F468}\u{1F3FE}\u200D\u2695\uFE0F'
  5. // → 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. 结合 --

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

2.4. 结合 &&

  1. const re = /[\p{Script_Extensions=Greek}&&\p{Letter}]/v;
  2. re.test('π'); // → true
  3. re.test('??'); // → false
  4. const re2 = /[\p{White_Space}&&\p{ASCII}]/v;
  5. re2.test('\n'); // → true
  6. re2.test('\u2028'); // → false

3. V 标志与 U 标志有何不同

  1. 使用新语法的无效模式现在变得有效
  2. 一些以前有效的模式现在是错误的,特别是那些字符类包含未转义特殊字符 ( ) [ { } / - | 的模式或双标点符号
  3. u 标志存在令人困惑的不区分大小写的匹配行为。 v 标志具有不同的、改进的语义

引用

原文链接:https://www.cnblogs.com/risheng/p/18189095

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号