ES 新特性全解密!這 25 個特性讓你的代碼效率飆升 50%
JavaScript 作為最流行的編程語言之一,通過 ECMAScript 標準的不斷演進,為開發者帶來了大量實用的新特性。分享 25 個能顯著提升編程效率的 ES 新特性,讓我們的代碼更簡潔、更優雅、更高效。
1. 可選鏈操作符(Optional Chaining)
告別繁瑣的空值檢查,用簡單的 ?. 優雅處理對象屬性訪問。
// 之前的寫法
const street = user && user.address && user.address.street;
// 現在的寫法
const street = user?.address?.street;
2. 空值合并運算符(Nullish Coalescing)
使用 ?? 來處理 null 或 undefined 的默認值設置。
const value = null;
const defaultValue = value ?? 'default'; // 'default'
3. 私有類字段(Private Class Fields)
使用 # 聲明私有字段,增強面向對象編程的封裝性。
class Person {
#name;
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
4. 動態導入(Dynamic Import)
按需加載模塊,優化應用性能。
button.addEventListener('click', async () => {
const module = await import('./feature.js');
module.doSomething();
});
5. Array.prototype.flat() 和 flatMap()
輕松處理嵌套數組。
const nested = [1, [2, 3], [4, [5, 6]]];
const flattened = nested.flat(2); // [1, 2, 3, 4, 5, 6]
6. 對象字面量增強
更簡潔的對象屬性和方法定義。
const name = 'Tom';
const age = 18;
const person = {
name,
age,
sayHi() {
console.log('Hi!');
}
};
7. Promise.allSettled()
等待所有 Promise 完成,無論成功與否。
const promises = [
fetch('/api/1'),
fetch('/api/2'),
fetch('/api/3')
];
const results = await Promise.allSettled(promises);
8. BigInt
處理超大整數。
const bigNumber = 9007199254740991n;
const result = bigNumber + 1n;
9. globalThis
統一的全局對象訪問方式。
// 在任何環境下都可用
console.log(globalThis);
10. String.prototype.matchAll()
更強大的字符串匹配能力。
const str = 'test1test2test3';
const regexp = /test(\d)/g;
const matches = [...str.matchAll(regexp)];
11. 邏輯賦值運算符
簡化條件賦值操作。
// 邏輯與賦值
x &&= y; // 等同于 x && (x = y)
// 邏輯或賦值
x ||= y; // 等同于 x || (x = y)
// 空值合并賦值
x ??= y; // 等同于 x ?? (x = y)
12. Promise.any()
返回第一個成功的 Promise。
const promises = [
fetch('/api/1'),
fetch('/api/2'),
fetch('/api/3')
];
try {
const first = await Promise.any(promises);
console.log(first);
} catch (error) {
console.log('All promises rejected');
}
13. 數字分隔符
提高大數字的可讀性。
const billion = 1_000_000_000;
const bytes = 0xFF_FF_FF_FF;
14. String.prototype.replaceAll()
替換字符串中的所有匹配項。
15. WeakRef 和 FinalizationRegistry
更好的內存管理機制。
16. 頂層 await
在模塊頂層使用 await。
17. 類靜態初始化塊
更靈活的類靜態成員初始化。
18. at() 方法
更直觀的數組索引訪問。
19. Object.hasOwn()
安全的屬性檢查方法。
20. 錯誤原因(Error Cause)
更好的錯誤追蹤。
21. Object.groupBy()
數組分組操作。
22. 正則表達式命名捕獲組
更清晰的正則表達式匹配結果。
23. Promise.withResolvers()
更優雅的 Promise 控制。
24. Array 復制方法
方便的數組操作。
const arr = [1, 2, 3];
const copy = arr.toReversed(); // 不修改原數組
const sorted = arr.toSorted(); // 不修改原數組
25. 裝飾器
增強類和類成員的功能。
function logged(target, context) {
return class extends target {
exec(...args) {
console.log('Starting execution...');
const result = super.exec(...args);
console.log('Finished execution.');
return result;
}
};
}
@logged
class Example {
exec() {
// ...
}
}