Skip to content

不正确数组方法

快速摘要

你 used 错误数组方法 — splice mutates 虽然 slice 复制, forEach 返回 undefined 虽然映射返回新 数组.

为什么发生

  • Confusing slice (复制) 使用 splice (mutate)

  • Using forEach 当你 需要映射 (or vice versa)

  • Confusing 查找 (首先 match) 使用筛选 (所有 matches)

最小示例

✗ 错误代码
const arr = [1, 2, 3, 4, 5];
const result = arr.splice(1, 2); // Mutates arr!
console.log(arr); // [1, 4, 5] — original changed!
console.log(result); // [2, 3]
✓ 修复代码
const arr = [1, 2, 3, 4, 5];
const result = arr.slice(1, 3); // Does NOT mutate
console.log(arr); // [1, 2, 3, 4, 5] — original intact
console.log(result); // [2, 3]

splice 修改原始数组 and 返回移除元素. slice 返回复制的 部分不使用修改原始. Using slice 当你 做不 想要到 mutate 是正确 choice.

如何诊断

  • 检查如果原始数组是 unexpectedly 修改

  • 验证返回值 matches 什么你 expect

  • 读取方法 documentation 到确认它的 behavior

如何修复

  • Use 正确方法 for 你的 intent (slice 到复制, splice 到修改)

  • Use 映射当 你需要新 数组, forEach for 边副作用

  • Use 查找 for one result, 筛选 for 多个 results

如何预防

  • Review 数组方法 documentation 之前 use

  • 测试使用小 数组到 验证 behavior

相关资源

相关术语

相关课程

  • 数组

    学习关于数组方法.

← 返回语言