JavaScript (MDN)
该技能将 MDN JavaScript 指南和参考手册浓缩为区别于习惯的内容:陷阱、令人惊讶的默认值、已弃用的 API 及其替代品,以及 MDN 推荐的模式。参考文件中的每条声明末尾都附有对应的 MDN 页面来源。省略了每个 JavaScript 开发者都应熟知的基础知识。
版本覆盖
MDN 跟踪活跃的 ECMAScript 标准,没有版本化路径。它还记录了 TC39 阶段 3 的特性(在正式定稿之前),因此示例可能使用尚未在所有环境中可用的特性。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript
较新的特性可能可用性有限。在依赖某个特性(如 Temporal、迭代器辅助方法、using、Promise.try、RegExp.escape、Error.isError、Math.sumPrecise、Uint8Array.fromBase64、Set 方法、Map.prototype.getOrInsert)之前,请检查目标运行时环境。MDN 标记为实验性的项目已在参考文件中标注。
如何导航
- 阅读下面的最高价值规则。它们涵盖了最频繁的错误。
- 根据末尾的表格,打开与任务匹配的参考文件。每个文件都是独立的。与时区、夏令时或持续时间相关的任务需要同时打开两个 Temporal 文件。与清理或
using相关的任务需要打开迭代器与资源管理文件。 - 当修改旧代码时,阅读匹配文件末尾的“旧模式”表格。
最高价值规则
- 使用
??作为默认值,而不是||,并且永远不要不加括号混合使用它们。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing - 使用
===。仅当需要区分-0和+0时使用Object.is()。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Equality_comparisons_and_sameness - 使用
Object.hasOwn()测试自有属性,永远不要与undefined比较。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn - 对于仅在运行时已知的键,使用
Map,而不是普通对象。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map#%E5%AF%B9%E8%B1%A1_vs._Map - 永远不要扩展
Object.prototype或内置原型。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain - 使用
structuredClone()进行深拷贝。展开操作符和Object.assign()是浅拷贝。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - 从箭头函数返回对象字面量时必须加括号:
return ({ ... }),单独的花括号会被视为代码块。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions#%E5%87%BD%E6%95%B0%E4%BD%93 - 使用
#private字段,并使用#x in obj进行品牌检查。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/Private_elements - 在
finally块中如果返回或抛出,会吞掉挂起的错误。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/try...catch - 抛出
Error对象,并使用new Error(msg, { cause })包装原因。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Error/cause - 在
then回调中返回每个 Promise,并以一个catch结束链。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises - 使用
Promise.all()同时启动独立的异步工作,而不是顺序await。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function forEach既不会提前停止,也不会等待异步回调。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach- 使用
Promise.try()提升同步或异步回调。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/try - 使用
using/await using或DisposableStack释放资源。永远不要依赖FinalizationRegistry进行清理。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Resource_management await using file = await fs.open(...)需要两个await:一个用于获取,一个用于释放。异步清理应放在[Symbol.asyncDispose]中,因为[Symbol.dispose]返回的 Promise 不会被等待。释放器按逆序执行,来自代码体和释放器的错误会作为一个SuppressedError出现(error= 后发生的,suppressed= 先发生的)。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/await_using- 在迭代器上调用迭代器辅助方法,而不是将其展开到数组中。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Iterator
- 默认的
sort()按字符串比较:应传入(a, b) => a - b,并且优先使用toSorted()以保留原数组。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort - 使用
Object.groupBy()/Map.groupBy()进行分组,而不是reduce()。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce - 字符串是 UTF-16 码元:使用
Intl.Segmenter统计字素。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/length - 使用
encodeURIComponent()编码 URL 部分,而不是encodeURI()。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/encodeURI - 使用
RegExp.escape()转义模式中的用户文本。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/escape - 带有
g或y标志的正则表达式在多次调用间会保持lastIndex。优先使用matchAll()。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test - 使用
Math.trunc()进行截断,为parseInt()传入基数,使用Number.isNaN()。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/parseInt - 超过 2^53 的整数需要使用 BigInt,并且 JSON 会损坏它们,除非使用字符串、
JSON.rawJSON或context.source。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON - 对于任何与安全相关的内容,使用
crypto.getRandomValues(),永远不要用Math.random()。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/random - 优先使用
Temporal而不是遗留的Date。Temporal 对象在<和-操作符上会抛出错误:应使用compare()。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date - 在
ZonedDateTime中使用 IANA 时区名称,而不是固定偏移量。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime#%E6%97%B6%E5%8C%BA%E5%92%8C%E5%81%8F%E7%A7%BB%E9%87%8F - 保持带时区的值带时区:
toPlainDateTime()会丢弃时区,导致后续运算忽略夏令时。ZonedDateTime.from()需要[zone]注释(使用Instant.from()解析纯偏移量字符串),并且ZonedDateTime.since()默认以小时为单位(跨越夏令时结束时为PT25H),除非传入largestUnit。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Temporal/ZonedDateTime - 重用单个
Intl格式化器,并且永远不要将其输出与固定字符串比较。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Internationalization#%E6%A0%BC%E5%BC%8F%E5%8C%96%E6%95%B0%E6%8D%AE - 使用
with { type: "json" }加载 JSON 模块,并使用import.meta.resolve()解析说明符。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Modules#%E5%8A%A0%E8%BD%BD%E9%9D%9E-javascript-%E8%B5%84%E6%BA%90 - 避免依赖
Symbol.species:引擎正在研究将其移除。https://developer.mozilla.org/zh-CN/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 规则、revivers、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 时区、夏令时消歧与 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 中。