ES2026 新特性整理

ES2026 是 JavaScript 的最新标准,带来了一系列实用的新特性。本文整理了主要的新功能。

1. Temporal API

终于有了靠谱的日期时间 API!告别 Date 对象的各种坑。

1
2
3
4
5
6
7
8
9
10
11
12
// 获取当前时间
const now = Temporal.Now.plainDateTimeISO();
console.log(now.toString()); // 2026-03-24T15:05:00

// 创建特定日期
const birthday = Temporal.PlainDate.from("2026-12-25");

// 日期运算
const tomorrow = now.add({ days: 1 });

// 时区处理
const zoned = Temporal.Now.zonedDateTimeISO("Asia/Shanghai");

Temporal 解决了 Date 的所有痛点:

  • 不可变对象
  • 时区支持完善
  • API 设计合理
  • 支持多种日历系统

2. Set 方法

Set 终于有了数学运算方法!

1
2
3
4
5
6
7
8
9
10
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);

a.intersection(b); // Set {2, 3} 交集
a.union(b); // Set {1, 2, 3, 4} 并集
a.difference(b); // Set {1} 差集
a.symmetricDifference(b); // Set {1, 4} 对称差集
a.isSubsetOf(b); // false
a.isSupersetOf(b); // false
a.isDisjointFrom(b); // false

3. Iterator Helpers

迭代器链式操作,像数组方法一样方便。

1
2
3
4
5
6
7
8
const numbers = [1, 2, 3, 4, 5].values();

const result = numbers
.filter(x => x % 2 === 0)
.map(x => x * 2)
.take(2);

console.log([...result]); // [4, 8]

支持的方法:

  • map(), filter(), take(), drop()
  • flatMap(), reduce(), toArray()
  • forEach(), some(), every(), find()

4. Promise.withResolvers

不再需要 new Promise 的回调嵌套。

1
2
3
4
5
6
7
8
9
10
// 以前
const promise = new Promise((resolve, reject) => {
// ...
});

// 现在
const { promise, resolve, reject } = Promise.withResolvers();

// 在任何地方调用
setTimeout(() => resolve("done"), 1000);

5. Array.fromAsync

轻松将异步迭代器转为数组。

1
2
3
4
5
6
7
8
async function* generateNumbers() {
yield 1;
yield 2;
yield 3;
}

const numbers = await Array.fromAsync(generateNumbers());
console.log(numbers); // [1, 2, 3]

6. Decorators(装饰器)

正式版的装饰器语法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function logged(value, { kind, name }) {
if (kind === "method") {
return function (...args) {
console.log(`calling ${name}`);
return value.call(this, ...args);
};
}
}

class Example {
@logged
greet(name) {
return `Hello, ${name}`;
}
}

7. Import Attributes

导入 JSON、CSS 等非 JS 模块。

1
2
import config from "./config.json" with { type: "json" };
import styles from "./styles.css" with { type: "css" };

浏览器支持

这些特性正在逐步落地各浏览器和 Node.js。使用前建议检查兼容性,或通过 Babel 等工具转译。


ES2026 让 JavaScript 更加成熟和好用。Temporal API 和 Set 方法尤其值得期待!

Happy coding!