JavaScript (MDN)
此技能濃縮了 MDN JavaScript 指南與參考資料,聚焦於與習慣用法不同的部分:常見陷阱、令人意外的預設行為、已棄用 API 及其替代方案,以及 MDN 推薦的模式。參考文件中的每個主張結尾都附有其來源的 MDN 頁面。基礎的 JavaScript 知識(每個開發者都知道的)則不在此列。
涵蓋的版本
MDN 追蹤最新的 ECMAScript 標準,沒有特定版本路徑。它也記錄了 TC39 第三階段的特性(在它們成為正式標準之前),因此範例可能使用了尚未普及的功能。 https://developer.mozilla.org/en-US/docs/Web/JavaScript
較新的功能可能可用性有限。在依賴某個功能(如 Temporal、迭代器輔助方法、using、Promise.try、RegExp.escape、Error.isError、Math.sumPrecise、Uint8Array.fromBase64、Set 方法、Map.prototype.getOrInsert)之前,請檢查目標執行環境。MDN 標記為實驗性的項目會在參考文件中標示。
如何瀏覽
- 閱讀下方最高優先級規則。這些規則能抓出最常見的錯誤。
- 根據表格開啟與任務相符的參考文件。每個檔案獨立存在。涉及時區、日光節約時間 (DST) 或持續時間的任務需要同時參考兩個 Temporal 檔案。涉及清理或
using的任務需要參考迭代器與資源管理檔案。 - 當修改舊程式碼時,請閱讀對應檔案末尾的「舊模式」表格。
最高優先級規則
- 預設使用
??而非||,且絕不混用兩者而不加括號。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing - 使用
===。僅在需要區分-0與+0時使用Object.is()。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Equality_comparisons_and_sameness - 使用
Object.hasOwn()測試自有屬性,絕不與undefined比較。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn - 對於僅在執行時期才知道的鍵,使用
Map,而非普通物件。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#objects_vs._maps - 絕不擴充
Object.prototype或內建原型。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain - 使用
structuredClone()進行深拷貝。展開運算符與Object.assign()只做淺拷貝。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - 箭頭函式返回物件字面量時需加上括號
({ ... }):單獨的大括號會被解讀為區塊。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#function_body - 使用
#private私有欄位,並用#x in obj進行品牌檢查。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_elements finally區塊中的return或throw會吞掉待處理的錯誤。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch- 拋出
Error物件,並使用new Error(msg, { cause })包裝原因。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause - 從
then回呼中返回每個 Promise,並以一個catch結束鏈結。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises - 使用
Promise.all()同時啟動獨立的非同步工作,而非依序使用await。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function forEach既不會提前停止,也不會await非同步回呼。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach- 使用
Promise.try()將同步或非同步回呼統一處理。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/try - 使用
using/await using或DisposableStack釋放資源。絕不依賴FinalizationRegistry進行清理。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Resource_management await using file = await fs.open(...)需要兩個await:一個用於獲取,一個用於釋放。非同步清理邏輯應放在[Symbol.asyncDispose]中,因為[Symbol.dispose]返回的 Promise 不會被await。可釋放資源的執行順序與建立順序相反,主體與可釋放資源拋出的錯誤會合併為一個SuppressedError(error= 後發生的錯誤,suppressed= 先發生的錯誤)。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/await_using- 直接在迭代器上呼叫迭代器輔助方法,而不是先展開到陣列中。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator
- 預設的
sort()會比較字串:請傳入(a, b) => a - b,並優先使用toSorted()以保留原始陣列。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort - 使用
Object.groupBy()/Map.groupBy()進行分組,而非reduce()。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce - 字串以 UTF-16 程式碼單元為單位:使用
Intl.Segmenter計算字素。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length - 使用
encodeURIComponent()編碼 URL 部分,而非encodeURI()。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI - 使用
RegExp.escape()跳脫模式中的使用者文字。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/escape - 重複使用的
g或y正則表達式會在每次呼叫間保留lastIndex。優先使用matchAll()。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test - 使用
Math.trunc()進行截斷,為parseInt()傳入基數,使用Number.isNaN()。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt - 大於 2^53 的整數需要使用 BigInt,且 JSON 會破壞它們,除非使用字串、
JSON.rawJSON或context.source。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON - 任何與安全相關的操作都應使用
crypto.getRandomValues(),絕不使用Math.random()。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random - 優先使用
Temporal而非舊有的Date。Temporal 物件在<和-運算符上會拋出錯誤:請使用compare()。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date - 在
ZonedDateTime中使用 IANA 時區名稱,而非固定偏移量。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime#time_zones_and_offsets - 保持含時區值的時區資訊:
toPlainDateTime()會丟棄時區,導致後續的算術運算忽略 DST。ZonedDateTime.from()需要[zone]註釋(使用Instant.from()解析純偏移量字串),且ZonedDateTime.since()預設以小時為單位(跨 DST 結束時為PT25H),除非你傳入largestUnit。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime - 重複使用同一個
Intl格式化器,切勿將其輸出與固定字串比較。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Internationalization#formatting_data - 使用
with { type: "json" }載入 JSON 模組,並使用import.meta.resolve()解析模組識別元。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#loading_non-javascript_resources - 避免依賴
Symbol.species:JavaScript 引擎正在評估移除它。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/species
參考文件
| 檔案 | 閱讀時機 |
|---|---|
| references/language-core-and-equality.md | == 與 ===、強制轉型、typeof、let/const/var 與暫時性死區、嚴格模式、ASI、八進位、執行模型、過時語法 |
| references/functions-and-classes.md | 箭頭函式與 this、預設與其餘參數、存取器、bind、類別欄位、#private、靜態區塊、extends、super |
| references/objects-prototypes-and-proxy.md | Object.hasOwn、assign、defineProperty、freeze、groupBy、原型、null 原型物件、Proxy、Reflect、Symbol、globalThis、eval |
| references/statements-and-operators.md | ??、?.、邏輯賦值、展開、解構賦值、delete、算術與位元運算陷阱、BigInt 運算符、比較、迴圈、switch、標籤、try/finally |
| references/async-and-promises.md | Promise 鏈、組合器、Promise.try、withResolvers、allKeyed、async/await 順序、未處理的拒絕、Promise 記憶體洩漏 |
| references/iterators-and-resource-management.md | 迭代協定、迭代器輔助方法、Iterator.zip/concat、產生器、using、await using、DisposableStack、SuppressedError、WeakRef、FinalizationRegistry |
| references/arrays-and-collections.md | 複製陣列方法、at、includes、findLast、sort、reduce、稀疏陣列、Array.from、Map、Set 方法、getOrInsert、WeakMap、WeakSet |
| references/strings.md | UTF-16、程式碼點與字素、localeCompare、normalize、replace 模式、replaceAll、matchAll、split、String.raw、URI 編碼 |
| references/regexp.md | RegExp.escape、方法選擇、lastIndex、y 與 d 標誌、u 與 v 模式、\p{...}、修飾符、錨點、群組、反向引用、後顧斷言 |
| references/numbers-math-json.md | 浮點數精確度、parseInt、四捨五入、toFixed、BigInt、Math.random、Math.sumPrecise、JSON.stringify 規則、復原函式、JSON.rawJSON |
| references/binary-data-and-shared-memory.md | 型別陣列、DataView 位元組序、可調整大小與可轉移的 ArrayBuffer、Uint8Array 的 base64 與十六進位、SharedArrayBuffer、Atomics |
| references/date-and-temporal.md | 從 Date 遷移到 Temporal、選擇 Temporal 型別、共通的 Temporal 規則、純日期與時間、維護 Date 程式碼 |
| references/temporal-time-zones-and-durations.md | ZonedDateTime、IANA 時區、DST 消歧與 offset、since/until、Duration 平衡與四捨五入、Temporal.Now |
| references/intl.md | 地區選擇與備援、DateTimeFormat、NumberFormat 數字選項、Collator、Segmenter、PluralRules、RelativeTimeFormat、ListFormat、DurationFormat |
| references/errors-and-debugging.md | cause、Error 子類別、Error.isError、AggregateError、堆疊追蹤、常見執行時期錯誤訊息及其修正 |
| references/modules.md | 模組與腳本、即時綁定、循環依賴、import()、import.meta、匯入屬性、import defer、import source、匯入映射 |
已爬取的頁面、版本說明與擷取日期列於 SOURCES.md。