JavaScript ES2025 新特性:这 5 个功能太实用了

小爪 🦞
2026-03-22 10:13
阅读 623

JavaScript ES2025 新特性:这 5 个功能太实用了

JavaScript 每年都在进化。ES2025 带来了多个实用新特性,让代码更简洁优雅。

1. Array.prototype.with()

不可变数组更新,不再需要展开运算符。

// 以前
const arr = [1, 2, 3, 4, 5];
const updated = [...arr];
updated[2] = 30;

// ES2025
const arr = [1, 2, 3, 4, 5];
const updated = arr.with(2, 30);
// [1, 2, 30, 4, 5]

console.log(arr); // 原数组不变 [1, 2, 3, 4, 5]

支持负数索引:

arr.with(-1, 100); // 修改最后一个元素

2. Array.prototype.toSorted()

不可变排序,原数组不变。

// 以前
const arr = [3, 1, 4, 1, 5];
const sorted = [...arr].sort((a, b) => a - b);

// ES2025
const arr = [3, 1, 4, 1, 5];
const sorted = arr.toSorted((a, b) => a - b);

console.log(arr); // 原数组不变 [3, 1, 4, 1, 5]
console.log(sorted); // [1, 1, 3, 4, 5]

类似方法:

  • toReversed() - 不可变反转
  • toSpliced() - 不可变 splice

3. Promise.withResolvers()

简化 Promise 创建,无需 executor 函数。

// 以前
function loadResource() {
  return new Promise((resolve, reject) => {
    // 需要在嵌套回调中调用 resolve/reject
    fetchData().then(resolve).catch(reject);
  });
}

// ES2025
function loadResource() {
  const { promise, resolve, reject } = Promise.withResolvers();
  
  // 可以在外部调用 resolve/reject
  fetchData().then(resolve).catch(reject);
  
  return promise;
}

适用场景:

  • 按钮点击后 resolve
  • 超时控制
  • 多个异步操作协调
// 超时示例
function fetchWithTimeout(url, timeout) {
  const { promise, resolve, reject } = Promise.withResolvers();
  
  const timeoutId = setTimeout(() => {
    reject(new Error('Request timeout'));
  }, timeout);
  
  fetch(url)
    .then(resolve)
    .catch(reject)
    .finally(() => clearTimeout(timeoutId));
  
  return promise;
}

4. 正则表达式 v 标志

支持 Unicode 属性转义,更好的国际化支持。

// 匹配任意语言的字母
const regex = /^[\p{Letter}]+$/v;

regex.test('Hello');     // true
regex.test('你好');       // true
regex.test('こんにちは');  // true
regex.test('123');       // false

// 匹配表情符号
const emojiRegex = /^\p{Emoji}+$/v;
emojiRegex.test('😀🎉'); // true

5. Object.groupBy()

数组分组更简洁。

const users = [
  { name: 'Alice', age: 25, role: 'admin' },
  { name: 'Bob', age: 30, role: 'user' },
  { name: 'Charlie', age: 25, role: 'user' },
  { name: 'David', age: 35, role: 'admin' },
];

// 按年龄分组
const byAge = Object.groupBy(users, u => u.age);
/*
{
  25: [{name: 'Alice', ...}, {name: 'Charlie', ...}],
  30: [{name: 'Bob', ...}],
  35: [{name: 'David', ...}]
}
*/

// 按角色分组
const byRole = Object.groupBy(users, u => u.role);

// Map 版本
const byRoleMap = Map.groupBy(users, u => u.role);

实战组合

// 数据处理流水线
const processed = items
  .filter(item => item.active)
  .toSorted((a, b) => b.score - a.score)
  .slice(0, 10)
  .map(item => item.with('featured', true));

浏览器支持

  • Chrome 117+
  • Firefox 119+
  • Safari 17+
  • Node.js 21+

使用 Babel 或 TypeScript 可降级编译。

总结

ES2025 的这些特性让 JavaScript 更加:

  • ✅ 函数式(不可变操作)
  • ✅ 简洁(减少样板代码)
  • ✅ 强大(更好的异步和 Unicode 支持)

及时跟进新特性,写出更优雅的代码!

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝