你可能錯過的16個ES2022 JavaScript新特性?

以下功能已經發布了好一段時間,如果覺得有用可以放心的用到真實的專案中。當然,也歡迎大家點贊、收藏、轉發。

1。私有欄位

你可能錯過的16個ES2022 JavaScript新特性?

以前,所有類欄位都必須在建構函式中定義,而且沒有私人屬性,可以從外部訪問所有欄位(當然可以透過技術手段遮蔽部分屬性,但是不再本文範圍之內)。比如下面的例子:

class Counter { constructor() { this。name = ‘Counter’; this。count = 0; } inc() { this。count++; }}

現在可以使用如下方法定義私有變數:

class Counter { name = ‘Counter’; #count = 0; // 私有屬性 inc() { this。#count++; }}

2。使用 in 關鍵字訪問私有欄位

你可能錯過的16個ES2022 JavaScript新特性?

私有屬性有一些問題,即當在沒有該私有屬性的物件上訪問私有欄位時,將丟擲錯誤。那麼如何檢查一個物件是否有私有屬性呢?除了可以使用 try。。。catch 外,還可以使用 in 運算子。

class Counter { name = ‘Counter’; #count = 0; static isCounter(obj) { return #count in obj; }}const counter = new Counter();Counter。isCounter(counter);// true

3。 陣列和字串的 at()方法

你可能錯過的16個ES2022 JavaScript新特性?

可以透過 A[i] 來訪問位置 i 的陣列項, 但是如果 i 是負數,而且想從陣列的末尾獲取元素怎麼辦? 雖然可以寫成 A[A。length + i], 但不是很方便。 另一種方法是使用 A。slice(i)[0], 但效率不是很高。這種情況下可以考慮使用 at 運算子。

const A = [2, 4, 6, 8, 10];A。at(-1); // 10const S = ‘Hello World’;S。at(-1); // ‘d’

4。 使用 findLast() 從陣列的末尾查詢一個專案

你可能錯過的16個ES2022 JavaScript新特性?

在陣列中查詢元素可以使用 find() 方法,那麼如何從陣列末尾開始查詢元素?可以使用 reverse() 和 find(),或者編寫自己的函式:

const A = [1, 20, 3, 40, 5];function findBackward(A, predicate) { for (let i = A。length - 1; i >= 0; i——) { if (predicate(A[i])) { return A[i]; } } return -1;}findBackward(A, (x) => x % 10 == 0); // 40// be careful with this method!A。reverse()。find((x) => x % 10 == 0); // 40

現在可以使用 findLast() 和 findLastIndex() 方法:

const A = [1, 20, 3, 40, 5];A。find((v) => v % 10 == 0); // 20A。findLast((v) => v % 10 == 0); // 40A。findIndex((v) => v % 10 == 0); // 1A。findLastIndex((v) => v % 10 == 0); // 3A。findLastIndex((v) => v == 0); // -1

5。 使用 hasOwn() 替代 hasOwnProperty()

你可能錯過的16個ES2022 JavaScript新特性?

雖然有 Object。prototype。hasOwnProperty() 方法來檢查一個物件是否有一個屬性作為它的直接屬性,但是使用起來相當麻煩:

let hasOwnProperty = Object。prototype。hasOwnProperty;if (hasOwnProperty。call(object, ‘foo’)) { console。log(‘has property foo’);}

很顯然,上面的程式碼不能這麼寫:

object。hasOwnProperty(‘foo’);

請記住,JavaScript 是一種動態語言,可以為任何物件新增一個屬性。所以 hasOwnProperty() 可以被同名物件的屬性覆蓋。為了避免這種情況,可以使用 hasOwn() 方法:

if (Object。hasOwn(object, ‘foo’)) { console。log(‘has property foo’);}

6。 為 error 物件添加了 cause 屬性

你可能錯過的16個ES2022 JavaScript新特性?

像下面的錯誤處理程式碼很常見:

await fetch(‘https://example。com/data。csv’)。catch((err) => { throw new Error(‘failed to get: ’ + err。message);});

它所做的事情是用新錯誤包裝原始錯誤,但是原來的錯誤丟失了。現在可以使用 cause 屬性來儲存原始錯誤並在以後獲取它:

await fetch(‘https://example。com/data。csv’) 。catch((err) => { throw new Error(‘failed to get’, { cause: err }); }) 。catch((err) => { // err有cause屬性 console。log(‘cause’, err。cause); });

7。支援#!(Hashbang)

你可能錯過的16個ES2022 JavaScript新特性?

現在支援 Hashbang,可以直接在終端中執行 NodeJS 指令碼:

#!/usr/bin/env node‘use strict’;console。log(1);

或者如下方式:

#!/usr/bin/env nodeexport {};console。log(1);

8。使用replaceAll

replaceAll() 返回一個新字串,其中模式的所有匹配項都被替換項替換。模式可以是字串或正則表示式,替換項可以是字串或為每次匹配執行的函式。

let str = ‘I like apple ,I eat apple sometimes’; let newStr = str。replaceAll(‘apple’, ‘orange’); console。log(newStr); /**** Output ****/ //I like orange ,I eat orange sometimes

9。使用“BigInt”支援大數計算

JS 中的 “MAX_SAFE_INTEGER” 無法用於計算超過Number的數字:

let v = Math。pow(2, 55) === Math。pow(2, 55) + 1 // true console。log(v); let v2 = Math。pow(2, 55); console。log(v2); //36028797018963970 let v3 = Math。pow(2, 55) + 1; console。log(v3); //36028797018963970

可以使用BigInt來替代:

BigInt(Math。pow(2, 55)) === BigInt(Math。pow(2, 55)) + BigInt(1) // false

10。數字分隔符

新引入的值分隔符使用 _(下劃線)字元來分隔值組,使它們更易於閱讀

let count = 1_000;let number = 1_000_000;let account = 1_000。0_001;

11。使用String。prototype。trimStart() / String。prototype。trimEnd()

String。prototype。trim()用於去除頭部和尾部的空格、換行等,現在頭部和尾部分別由trimStart()、trimEnd()控制,trimLeft(), trimRight() 是它們的別名。

let str = ‘ Hello JavaScript ’; str。trimLeft(); //‘Hello JavaScript ’ str。trimRight(); //‘ Hello JavaScript’

12。Array。prototype。flat() / Array。prototype。flatMap()

展平陣列是 Array 原型的一項新功能,它允許您透過傳入級別深度引數(預設值為 1)來提高展平陣列的級別。 如果你想提高到最高級別,你可以寫一個更大的數字,但不建議這樣做。 flatMap() 方法首先使用 map 函式對映每個元素,然後將結果展平到一個新陣列中。

const a1 = [1, 2, [3, 4]]。flat();console。log(a1); // [1, 2, 3, 4]const a2 = [1, 2, [3, 4, [5, 6]]]。flat(2);console。log(a2); // [1, 2, 3, 4, 5, 6]const a3 = [1, 2, 3, 4]。flatMap(v => [v, v * 2]);console。log(a3); // [1, 2, 2, 4, 3, 6, 4, 8]

13。將catch引數改為可選

在 try。。。catch 錯誤處理期間,如果沒有向 catch 傳遞引數,程式碼將報告錯誤。在新規範中,可以省略 catch 繫結引數和括號。

try{ return true;}catch{ return false;}

14。空合併運算子 (???)

當左運算元為 null 或undefined時,它返回右運算元。否則,它返回左邊的運算元。

const str = null ?? ‘default string’;console。log(str);// expected output: “default string”const num = 0 ?? 42;console。log(num);// expected output: 0/** Note * Unlike the logical or (||) operator, the logical or returns the right-hand operand if the left operand is false, e。g。 ‘’ or 0 */

15。可選鏈運算子 (?。)

如果訪問物件上不存在的屬性,請使用 ?。運算子。

let obj = {};console。log(obj。person。name)// Cannot read properties of undefined (reading ‘name’)console。log(obj。?person?。name)// expected output:undefine

16。Object。fromEntries()

Object。entries 將物件轉換為 [key, value] 鍵值對。 object。fromEntries() 用於將鍵值對縮減為物件結構。

const entries = [[‘name’, ‘maxwell’]]; console。log(entries); const object = Object。fromEntries(entries); console。log(object);

你可能錯過的16個ES2022 JavaScript新特性?

參考資料

https://betterprogramming。pub/new-features-in-javascript-2022-b3ffadd1b261

https://javascript。plainenglish。io/10-new-javascript-features-you-must-learn-54f9a622b0c6