普通视图

发现新文章,点击刷新页面。
今天 — 2025年7月3日首页

ES2020 都有哪些新写法?

2025年7月3日 17:53

1、可选链操作符

// 传统写法
const street = user && user.address && user.address.street;

// ES2020
const street = user?.address?.street; // 任意一环不存在则返回 undefined

支持的场景:

  • 属性访问 obj?.prop
  • 动态属性 obj?.[expr]
  • 函数调用 func?.()

2、空值合并运算符

作用:精准判断 null/undefined(不包含其他假值如 0 或 '')。

// 传统写法
const value = input !== null && input !== undefined ? input : 'default';

// ES2020
const value = input ?? 'default'; // 仅在 input 为 null/undefined 时生效

对比 ||

const count = 0;
console.log(count || 10); // 10(0 是假值)
console.log(count ?? 10); // 0(精准判断)

3、动态导入

作用:按需异步加载模块。

// 传统静态导入
import module from 'module';

// ES2020 动态导入
button.addEventListener('click', async () => {
  const module = await import('./module.js');
  module.doSomething();
});

4、 BigInt 大整数类型

作用:表示超出 Number.MAX_SAFE_INTEGER 的整数。

Number.MAX_SAFE_INTEGER 是多少?

2^53 - 1 = 9007199254740991

技术背景:

JS使用 IEEE 754 标准的64位双精度浮点数表示所有数字(包括整数) 其中52位用于表示整数部分的尾数

5、Promise.allSettled()

获取所有Promise的结果(无论成功还是失败)

6、String.matchAll()

作用:高效遍历正则匹配的所有分组。

const str = 'test1test2';
const regex = /t(e)(st(\d?))/g;

// 传统写法:循环 exec
// ES2020
const matches = [...str.matchAll(regex)];
matches[0]; // ["test1", "e", "st1", "1", index: 0, ...]

七、globalThis

作用:统一全局对象访问(跨浏览器/Node.js 环境)。

// 传统环境判断
const global = typeof window !== 'undefined' ? window : global;

// ES2020
console.log(globalThis); // 浏览器: window, Node.js: global

八、模块新特性

1. import.meta

console.log(import.meta.url); // 文件 URL(如 "file:///path/to/module.js")

2. 导出命名空间

export * as utils from './utils.js'; // 将模块所有导出作为命名空间

九、for-in 机制标准化

明确规范 for-in 循环的遍历顺序(虽实际仍依赖引擎实现)

IEEE 754 双精度浮点数标准,最大整数和最大的数字

2025年7月3日 16:02

基础:

  1. 所有的数字,都是用 64位双精度浮点数 表示,其内存结构分为3部分

[1位符号位][11位指数位][52位尾数位] 来存储的

符号位:决定数字的正负(0是正数,1是负数)

指数位:表示2的幂次(采用偏移码表示,实际指数 = 存储值 - 1023)

范围:-1022 到 1023(特殊值 0 和 2047用于表示0和无穷大)

尾数位/有效数字(52 bits + 隐含位)

  • 关键点:实际精度是 53 bits(52位显式存储 + 1位隐含的"1") 采用"隐含前导1"的表示法(normalized numbers)

综上: 数值的计算公式为:

image.png

最大整数Number.MAX_SAFE_INTEGER

2^53 -1

最大值:Number.MAX_VALUE

image.png

昨天以前首页
❌
❌