所有分类
  • 所有分类
  • Html5资源
  • React资源
  • Vue资源
  • Php资源
  • ‌小程序资源
  • Python资源

ECMAScript 2025 (ES2025) 新特性详解

1. 数组方法增强

1.1 Array.prototype.groupBy()

语法

array.groupBy(callbackFn)

参数

  • callbackFn:分组函数,接收三个参数:
  • element:当前元素
  • index:当前索引
  • array:原数组
  • 返回值:作为分组的键

特性

  • 不改变原数组
  • 返回一个新的对象
  • 键为分组条件,值为对应分组的数组
  • 支持链式调用

示例详解

// 基本使用
const numbers = [1, 2, 3, 4, 5, 6];
const grouped = numbers.groupBy(num => num % 2 === 0 ? 'even' : 'odd');
// 结果:
// {
//   'odd': [1, 3, 5],
//   'even': [2, 4, 6]
// }

// 复杂对象分组
const users = [
  { name: '张三', age: 25, city: '北京', role: 'admin' },
  { name: '李四', age: 30, city: '上海', role: 'user' },
  { name: '王五', age: 25, city: '北京', role: 'user' }
];

// 按城市分组
const byCity = users.groupBy(user => user.city);
// 结果:
// {
//   '北京': [
//     { name: '张三', age: 25, role: 'admin' },
//     { name: '王五', age: 25, role: 'user' }
//   ],
//   '上海': [
//     { name: '李四', age: 30, role: 'user' }
//   ]
// }

// 按年龄和角色组合分组
const byAgeAndRole = users.groupBy(user => `${user.age}-${user.role}`);
// 结果:
// {
//   '25-admin': [{ name: '张三', city: '北京' }],
//   '30-user': [{ name: '李四', city: '上海' }],
//   '25-user': [{ name: '王五', city: '北京' }]
// }

// 链式调用
const result = users
  .groupBy(user => user.city)
  .groupBy(group => group.length > 1 ? 'multiple' : 'single');

1.2 Array.prototype.groupByToMap()

语法

array.groupByToMap(callbackFn)

参数

  • callbackFn:分组函数,与 groupBy() 相同

特性

  • 返回 Map 对象
  • 保持键值对的插入顺序
  • 可以使用任意类型的键
  • 适合需要保持顺序的场景

示例详解

// 基本使用
const products = [
  { id: 1, category: '电子产品', price: 1000, stock: 10 },
  { id: 2, category: '食品', price: 50, stock: 100 },
  { id: 3, category: '电子产品', price: 2000, stock: 5 }
];

// 按类别分组
const byCategory = products.groupByToMap(product => product.category);
// 结果:
// Map {
//   '电子产品' => [
//     { id: 1, price: 1000, stock: 10 },
//     { id: 3, price: 2000, stock: 5 }
//   ],
//   '食品' => [
//     { id: 2, price: 50, stock: 100 }
//   ]
// }

// 使用对象作为键
const byPriceRange = products.groupByToMap(product => ({
  min: Math.floor(product.price / 1000) * 1000,
  max: Math.ceil(product.price / 1000) * 1000
}));
// 结果:
// Map {
//   { min: 0, max: 1000 } => [{ id: 2, price: 50, stock: 100 }],
//   { min: 1000, max: 2000 } => [{ id: 1, price: 1000, stock: 10 }],
//   { min: 2000, max: 3000 } => [{ id: 3, price: 2000, stock: 5 }]
// }

2. 对象方法增强

2.1 Object.groupBy()

语法

Object.groupBy(items, callbackFn)

参数

  • items:要分组的对象数组
  • callbackFn:分组函数,与 Array.prototype.groupBy() 相同

特性

  • 静态方法
  • 适用于任何可迭代对象
  • 返回普通对象
  • 与 Array.prototype.groupBy() 功能类似

示例详解

// 基本使用
const students = [
  { name: '小明', grade: 'A', subject: '数学', score: 95 },
  { name: '小红', grade: 'B', subject: '语文', score: 88 },
  { name: '小刚', grade: 'A', subject: '数学', score: 92 }
];

// 按成绩等级分组
const byGrade = Object.groupBy(students, student => student.grade);
// 结果:
// {
//   'A': [
//     { name: '小明', subject: '数学', score: 95 },
//     { name: '小刚', subject: '数学', score: 92 }
//   ],
//   'B': [
//     { name: '小红', subject: '语文', score: 88 }
//   ]
// }

// 按科目和成绩组合分组
const bySubjectAndScore = Object.groupBy(students, student => 
  `${student.subject}-${student.score >= 90 ? '优秀' : '良好'}`
);
// 结果:
// {
//   '数学-优秀': [
//     { name: '小明', grade: 'A', score: 95 },
//     { name: '小刚', grade: 'A', score: 92 }
//   ],
//   '语文-良好': [
//     { name: '小红', grade: 'B', score: 88 }
//   ]
// }

3. 异步编程增强

3.1 Promise.withResolvers()

语法

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

特性

  • 返回包含三个属性的对象:
  • promise:Promise 实例
  • resolve:resolve 函数
  • reject:reject 函数
  • 避免闭包污染
  • 更好的代码组织

示例详解

// 基本使用
function createDeferred() {
  const { promise, resolve, reject } = Promise.withResolvers();
  return { promise, resolve, reject };
}

// 实现可取消的 Promise
function createCancellablePromise(executor) {
  const { promise, resolve, reject } = Promise.withResolvers();
  let cancelled = false;

  const cancel = () => {
    cancelled = true;
    reject(new Error('Operation cancelled'));
  };

  executor(resolve, reject, () => cancelled);

  return { promise, cancel };
}

// 使用示例
const { promise, cancel } = createCancellablePromise((resolve, reject, isCancelled) => {
  const timer = setTimeout(() => {
    if (isCancelled()) return;
    resolve('Operation completed');
  }, 1000);

  return () => clearTimeout(timer);
});

// 可以随时取消操作
setTimeout(() => cancel(), 500);

// 实现带超时的 Promise
function timeoutPromise(promise, timeout) {
  const { promise: timeoutPromise, resolve, reject } = Promise.withResolvers();
  
  const timer = setTimeout(() => {
    reject(new Error('Operation timed out'));
  }, timeout);

  promise
    .then(result => {
      clearTimeout(timer);
      resolve(result);
    })
    .catch(error => {
      clearTimeout(timer);
      reject(error);
    });

  return timeoutPromise;
}

4. 类型系统增强

4.1 类型注解

语法

// 基本类型
let variable: type;

// 函数类型
function name(param: type): returnType {}

// 接口
interface Name {
  property: type;
}

// 泛型
function name<T>(param: T): T {}

特性

  • 静态类型检查
  • 更好的 IDE 支持
  • 更清晰的代码文档
  • 减少运行时错误

示例详解

// 基本类型
let num: number = 42;
let str: string = 'hello';
let bool: boolean = true;
let arr: number[] = [1, 2, 3];
let tuple: [string, number] = ['hello', 42];

// 函数类型
function add(a: number, b: number): number {
  return a + b;
}

// 接口
interface User {
  name: string;
  age: number;
  email?: string;  // 可选属性
  readonly id: number;  // 只读属性
}

// 泛型
function identity<T>(arg: T): T {
  return arg;
}

// 高级类型
type Status = 'success' | 'error' | 'pending';

type UserWithRole = User & {
  role: 'admin' | 'user';
};

type PartialUser = Partial<User>;

type ReadonlyUser = Readonly<User>;

// 条件类型
type NonNullable<T> = T extends null | undefined ? never : T;

// 映射类型
type Optional<T> = {
  [P in keyof T]?: T[P];
};

5. 模块系统增强

5.1 导入断言

语法

import module from 'path' assert { type: 'moduleType' };

特性

  • 提供模块类型信息
  • 增强类型安全性
  • 支持多种模块类型
  • 更好的工具支持

示例详解

// 导入 JSON
import config from './config.json' assert { type: 'json' };

// 导入 WebAssembly
import wasm from './module.wasm' assert { type: 'webassembly' };

// 导入 CSS
import styles from './styles.css' assert { type: 'css' };

// 动态导入
const loadModule = async () => {
  const module = await import('./module.js', {
    assert: { type: 'javascript' }
  });
};

// 组合使用
import { 
  default as data,
  metadata 
} from './data.json' assert { 
  type: 'json',
  integrity: 'sha256-...'
};

6. 字符串处理增强

6.1 String.prototype.replaceAll()

语法

str.replaceAll(searchValue, replaceValue)

参数

  • searchValue:要替换的子串或正则表达式
  • replaceValue:替换值,可以是字符串或函数

特性

  • 替换所有匹配项
  • 支持字符串和正则表达式
  • 不改变原字符串
  • 返回新字符串

示例详解

// 基本使用
const text = 'Hello World, Hello JavaScript';
const newText = text.replaceAll('Hello', 'Hi');
// 结果: 'Hi World, Hi JavaScript'

// 使用正则表达式
const html = '<div>Hello</div><div>World</div>';
const escaped = html.replaceAll(/<div>/g, '&lt;div&gt;');

// 使用函数作为替换值
const numbers = '1 2 3 4 5';
const doubled = numbers.replaceAll(/\d+/g, match => match * 2);
// 结果: '2 4 6 8 10'

// 复杂替换
const template = 'Hello ${name}, welcome to ${place}';
const replaced = template.replaceAll(/\${(\w+)}/g, (match, key) => {
  const values = { name: '张三', place: '北京' };
  return values[key] || match;
});
// 结果: 'Hello 张三, welcome to 北京'

7. 数字处理增强

7.1 数字分隔符

语法

const number = 1_000_000;

特性

  • 提高数字可读性
  • 支持多种进制
  • 不影响数值
  • 不能出现在数字开头或结尾

示例详解

// 大数字
const billion = 1_000_000_000;
const million = 1_000_000;

// 小数
const pi = 3.141_592_653_589_793;
const smallNumber = 0.000_001;

// 不同进制
const binary = 0b1010_1010;
const hex = 0xFF_FF_FF;
const octal = 0o777_777;

// 科学计数法
const scientific = 1.23e10_000;

// 实际应用
const config = {
  maxFileSize: 10_000_000,  // 10MB
  timeout: 30_000,          // 30秒
  retryCount: 3_000,        // 重试次数
  precision: 0.000_001      // 精度
};

8. 错误处理增强

8.1 Error.cause

语法

new Error(message, { cause: error })

特性

  • 提供错误链
  • 更好的错误追踪
  • 更清晰的错误上下文
  • 支持嵌套错误

示例详解

// 基本使用
try {
  try {
    throw new Error('原始错误');
  } catch (error) {
    throw new Error('新错误', { cause: error });
  }
} catch (error) {
  console.log(error.cause); // 输出原始错误
}

// 实际应用
async function fetchUserData(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`);
    if (!response.ok) {
      throw new Error('HTTP error', { 
        cause: new Error(`Status: ${response.status}`) 
      });
    }
    return await response.json();
  } catch (error) {
    throw new Error('Failed to fetch user data', { cause: error });
  }
}

// 错误处理
try {
  await fetchUserData(123);
} catch (error) {
  console.error('Error:', error.message);
  console.error('Caused by:', error.cause);
  if (error.cause?.cause) {
    console.error('Root cause:', error.cause.cause);
  }
}

9. 性能优化特性

9.1 WeakRef

语法

const weakRef = new WeakRef(target);

特性

  • 创建弱引用
  • 不阻止垃圾回收
  • 适合缓存系统
  • 避免内存泄漏

示例详解

// 基本使用
const obj = { data: 'important' };
const weakRef = new WeakRef(obj);

// 检查引用
if (weakRef.deref()) {
  console.log('对象仍然存在');
} else {
  console.log('对象已被回收');
}

// 缓存系统实现
class Cache {
  constructor() {
    this.cache = new Map();
  }

  set(key, value) {
    this.cache.set(key, new WeakRef(value));
  }

  get(key) {
    const ref = this.cache.get(key);
    if (ref) {
      const value = ref.deref();
      if (value === undefined) {
        this.cache.delete(key);
      }
      return value;
    }
    return undefined;
  }

  cleanup() {
    for (const [key, ref] of this.cache.entries()) {
      if (!ref.deref()) {
        this.cache.delete(key);
      }
    }
  }
}

// 使用示例
const cache = new Cache();
const largeObject = { /* 大对象 */ };
cache.set('key', largeObject);

// 定期清理
setInterval(() => cache.cleanup(), 60_000);

10. 其他实用特性

10.1 逻辑赋值运算符

语法

a ||= b;  // 逻辑或赋值
a &&= b;  // 逻辑与赋值
a ??= b;  // 空值合并赋值

特性

  • 简化条件赋值
  • 减少代码重复
  • 提高可读性
  • 保持代码简洁

示例详解

// 默认值设置
function processOptions(options) {
  options.timeout ||= 1000;  // 如果 timeout 为假值,设置为 1000
  options.retry ??= 3;      // 如果 retry 为 null 或 undefined,设置为 3
}

// 条件执行
function validateInput(input) {
  input &&= input.trim();  // 如果 input 为真值,则执行 trim()
}

// 对象属性初始化
class User {
  constructor(data) {
    this.name = data.name;
    this.email ??= 'default@example.com';
    this.settings ||= {};
  }
}

// 实际应用
function createUser(data) {
  const user = {
    name: data.name,
    email: data.email,
    preferences: data.preferences
  };

  // 设置默认值
  user.preferences ??= {};
  user.preferences.theme ||= 'light';
  user.preferences.language ??= 'zh-CN';

  return user;
}

总结

ES2025 的新特性主要集中在以下几个方面:

  1. 数据处理能力增强
  • 数组和对象的新方法
  • 更强大的分组功能
  • 更好的数据转换能力
  1. 异步编程改进
  • 更灵活的 Promise 控制
  • 更好的错误处理
  • 更清晰的异步代码结构
  1. 类型系统增强
  • 更强大的类型检查
  • 更好的类型推断
  • 更丰富的类型工具
  1. 模块系统改进
  • 更灵活的模块导入
  • 更好的类型支持
  • 更安全的模块加载
  1. 基础功能增强
  • 字符串处理改进
  • 数字表示优化
  • 错误处理增强
  1. 性能优化
  • 内存管理改进
  • 垃圾回收优化
  • 资源管理增强
  1. 语法糖
  • 更简洁的赋值操作
  • 更清晰的代码结构
  • 更好的可读性
原文链接:https://code.ifrontend.net/archives/301,转载请注明出处。
0

评论0

显示验证码
没有账号?注册  忘记密码?