终于,JavaScript 中的安全数组方法

There’s a good reason that many developers pause before using .sort(), .reverse(), or .splice() in JavaScript: those methods mutate the original array. That single side effect can lead to subtle, hard-to-trace bugs, especially in apps with shared or reactive state. The good news is that in the last couple of years we’ve gotten new array methods that make working with arrays safer and cleaner by avoiding mutation altogether:

许多开发者在使用 .sort().reverse().splice() 之前会犹豫,这是有充分理由的:这些方法会改变原始数组。仅此一个副作用就可能导致难以追踪的隐蔽 bug,尤其是在具有共享或响应式状态的应用中。好消息是,在过去几年里,我们获得了新的数组方法,它们通过完全避免改变原数组,让数组操作更安全、更简洁:

  • toSorted()
  • toSorted()
  • toReversed()
  • toReversed()
  • toSpliced()
  • toSpliced()

These return copies instead of changing the original array. It’s a small syntax upgrade with big implications, especially for React developers who rely on immutability to manage state.

这些方法返回副本而非修改原数组。虽然只是语法上的小幅升级,却意义重大,尤其对依赖不可变性来管理状态的 React 开发者而言。

The problem with in-place array methods

就地修改数组方法的问题

In JavaScript, traditional methods like .sort(), .reverse(), and .splice() mutate the array they’re called on:

在 JavaScript 中,传统方法如 .sort().reverse().splice() 会改变它们所调用的数组:

const numbers = [3, 1, 2];
numbers.sort(); console.log(numbers); 

In frameworks like React, this can lead to unexpected behavior when updating state, because mutating arrays directly doesn’t trigger re-renders.

在 React 这类框架中,直接修改数组会导致更新状态时触发意外的行为,因为直接突变数组不会触发重新渲染。

Comparing old vs. new

旧方法 vs. 新方法对比

Operation Mutating method Non-mutating alternative
Sort arr.sort() arr.toSorted()
Reverse arr.reverse() arr.toReversed()
Splice arr.splice() arr.toSpliced()
操作 会改变原数组的方法 不改变原数组的替代方法
排序 arr.sort() arr.toSorted()
反转 arr.reverse() arr.toReversed()
拼接/删除 arr.splice() arr.toSpliced()

These new methods behave similarly to their mutating counterparts, but return a new array instead of modifying the original.

这些新方法的行为与其对应的变异版本类似,但返回的是新数组,而非修改原数组。

⚠️ Note: These are shallow copies, so if your array contains objects, the objects themselves are still the same references.

⚠️ 注意: ...

开通本站会员,查看完整译文。

- 위키
Copyright © 2011-2025 iteam. Current version is 2.146.0. UTC+08:00, 2025-09-19 07:52
浙ICP备14020137号-1 $방문자$