ES2023 有哪些新功能?👀
去年我写了一篇关于ES2022新功能的文章,今年让我们来看看 ES2023 中即将推出的新功能。
ES2023 的功能
1. 从最后一个查找数组
此函数将允许我们根据条件从数组的最后一个元素到第一个元素进行查找。
const array = [{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}, {a: 4, b: 4}]
console.log(array.findLast(n => n)); //result -> {a: 4,b: 4 }
console.log(array.findLast(n => n.a * 5 === 20)); // result -> {a:4,b:4} as the condition is true so it returns the last element.
console.log(array.findLast(n => n.a * 5 === 21)); //result -> undefined as the condition is false so return undefined instead of {a:4,b:4}.
console.log(array.findLastIndex(n => n.a * 5 === 21)); // result -> -1 as the condition is not justified for returning the last element.
console.log(array.findLastIndex(n => n.a * 5 === 20)); // result -> 3 which is the index of the last element as the condition is true.
2. Hashbang 语法
此功能使我们能够在某些 CLI 中使用 Hashbang/Shebang。Shebang由#!
表示,它是脚本开头的一个特殊行,用于告诉操作系统在执行脚本时使用哪个解释器。
#!/usr/bin/env node
// in the Script Goal
'use strict';
console.log(2*3);
#!/usr/bin/env node
// in the Module Goal
export {};
console.log(2*2);
#!/usr/bin/env node
此行将直接调用 Node.js 源文件,作为其自身的可执行文件。
我们不需要此行(#!/usr/bin/env node)
通过节点解释器显式调用文件,例如,node ./file
3. Symbols 作为 WeakMap 的键
这允许使用唯一的符号作为键。目前,WeakMap 仅限于允许对象作为键。对象之所以被用作 WeakMap 的键,是因为它们共享相同的身份属性。
Symbol 是 ECMAScript 中唯一允许使用 Symbol 作为键来获取唯一值的原始类型,而不是使用 WeakMap 创建新对象。
const weak = new WeakMap();
const key = Symbol('my ref');
const someObject = { a:1 };
weak.set(key, someObject);
console.log(weak.get(key));
更多与ShadowRealms和使用符号作为 WeakMap 的记录和元组相关的用例
4. 通过复制更改数组
这提供了额外的方法来Array.prototype
更改数组,通过返回带有更改的新副本而不是更新原始数组。
新Array.prototype
引入的功能包括:
Array.prototype.toReversed()
Array.prototype.toSorted(compareFn)
Array.prototype.toSpliced(start, deleteCount, ...items)
Array.prototype.with(index, value)
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
/* toReversed */
const reversed = numbers.toReversed();
console.log("reversed", reversed); // "reversed", [9, 8, 7, 6, 5, 4, 3, 2, 1]
console.log("original", numbers); // "original", [1, 2, 3, 4, 5, 6, 7, 8, 9]
/* toSorted */
const sortedArr = numbers.toSorted();
console.log("sorted", sortedArr); // "sorted", [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log("original", numbers); // "original", [1, 2, 3, 4, 5, 6, 7, 8, 9]
/* with */
const replaceWith = numbers.with(1, 100);
console.log("with", replaceWith); // "with", [1, 100, 3, 4, 5, 6, 7, 8, 9]
console.log("original", numbers); // "original", [1, 2, 3, 4, 5, 6, 7, 8, 9]
/* toSpliced */
const splicedArr = numbers.toSpliced(0, 4);
console.log("toSpliced", splicedArr); // "toSpliced", [5, 6, 7, 8, 9]
console.log("original", numbers); // "original", [1, 2, 3, 4, 5, 6, 7, 8, 9]
ES2023 推出了一些很棒的功能,我非常期待在日常编码中亲自尝试它们。
编码愉快!👩💻
文章来源:https://dev.to/jasmin/what-is-new-in-es2023-4bcm