BigInt
早期的 JavaScript
中,不能正确表示过大的数字,大于 MAX_SAFE_INTEGER
的数值可能不正确,在 ES11 中,引入了新的数据类型 BigInt
,用于表示大的整数。
js
// ES11 之前 max_safe_ integer
const maxInt = Number.MAX_SAFE_INTEGER;
console.log(maxInt); // 9007199254740991
// ES11 之后:BigInt
const bigInt = 900719925474099100n;
// 打印 900719925474099110n,必须在10后加n
console.log(bigInt + 10n);
const num = 100;
// int 转换 BigInt
console.log(bigInt + BigInt(num));
?? Nullish Coalescing Operator 空值合并运算
一般用于设置变量默认值。
js
let foo = 0;
// 设置默认值,使用||的弊端,当foo为空字符串或为0时,会变成右边值
// let bar = foo || 'default value'
let bar = foo ?? "default value";
// 打印 0
console.log(bar);
? Optional Chaining 可选链
js
const info = {
name: "tom",
};
// 报错
console.log(info.friend.girlFriend.name);
// ES11之前
if (info && info.friend && info.friend.girlFriend) {
console.log(info.friend.girlFriend.name);
}
// ES11 简洁
console.log(info.friend?.girlFriend?.name);
Global This 全局对象
在之前我们希望获取 JavaScript
环境的全局对象,不同的环境获取的方式是不一样的:
- 在浏览器中可以通过
this
、window
来获取; - 在
Node
中我们需要通过global
来获取; 在 ES11 之后,可以直接访问globalThis
获取全局对象。
for ... in 标准化
js
const obj = {
name: "tom",
};
for (const key in obj) {
// ES11 规定 key 的值为对象的 key
console.log(key);
}
Dynamic Import 动态导入
js
import("/component").then();