2025 年每个 JavaScript 开发者都应该知道的一些特性

  • 发布时间及相关标签:2025 年 06 月 04 日发布,包含标签 #web#javascript#ecmascript
  • 图片JS symbol
  • JavaScript 新特性介绍

    • Iterator helpers:引入用于迭代器的方法,如[Iterator.prototype.drop()][Iterator.prototype.take()]等,可更高效地处理数组转换,避免创建临时数组,常见创建可迭代对象的方式有[Iterator.from()]values()方法等,如arr.values().drop(10).take(10).filter(el => el < 10).map(el => el + 5).toArray()更高效。需注意 Safari 从 2025 年 03 月 31 日开始支持该特性,最好等待数月。
    • Array at() method[Array.prototype.at()]可替代访问第 n 个元素的方式,支持负索引,如[10,20,30].at(-1)返回 30,比之前写arr[arr.length - 1]更简洁。
    • Promise.withResolvers():取代之前创建 Promise 解析器的繁琐代码,如const { promise, resolve, reject } = Promise.withResolvers();更方便。
    • String.prototype.replace() / String.prototype.replaceAll() callback:可在String.prototype.replace()String.prototype.replaceAll()的第二个参数中传递回调函数,替换字符串为回调函数返回的值,如let counter = 0; console.log("NUMBER, NUMBER, NUMBER".replaceAll("NUMBER", (match) => match + "=" + (++counter))),性能和内存效率高。
    • Swapping variables:替代传统交换变量的方式,如let a = 1, b = 2; [a, b] = [b, a];更简洁。
    • structuredClone():浏览器支持的用于深度复制对象的函数,比JSON.stringify()JSON.parse()更合适,可处理NaNundefined、循环引用等问题,如const obj = {}; obj.selfReference = obj; const clonedObj = structuredClone(obj);
    • Tagged templates:允许通过函数解析模板字面量,第一个参数为字符串数组,其余为表达式,可用于自动转换插值值,如function escapeHtml(strings,...args) { …… } console.log(escapeHtml
      ${'
      '});
    • WeakMap / WeakSet:类似于MapSet,但键不允许为基本类型且缺少迭代器,当键失去所有引用时可被垃圾回收,如const set = new WeakSet(); const map = new WeakMap();
    • Set operations:新增支持Set对象的布尔操作,如[Set.prototype.difference()][Set.prototype.intersection()]等,可进行集合的差集、交集等操作,如const set1 = new Set([1,2,3,4]); const set2 = new Set([3,4,5,6]); console.log(set1.difference(set2));等。
阅读 11
0 条评论