
本文讲解如何在 javascript 数组遍历中优雅实现相邻元素的滑动赋值:每次调用函数时,before 取当前元素,after 取前一个元素(首项为 null),末尾还可补全终态(before = null, after = 最后一项)。
本文讲解如何在 javascript 数组遍历中优雅实现相邻元素的滑动赋值:每次调用函数时,before 取当前元素,after 取前一个元素(首项为 null),末尾还可补全终态(before = null, after = 最后一项)。
在实际开发中,我们常需处理具有时序或位置依赖关系的数据流,例如构建链表结构、生成差分日志、实现滚动提示(如“上一条:X,当前:Y”),或为动画/状态机提供前后帧上下文。此时,简单使用 map() 或 forEach() 的默认参数(仅含当前项与索引)往往不够——关键信息“前一项”需要显式获取。
核心解法在于:利用数组迭代方法(如 forEach、map、for...of 配合 entries())自动传入的原始数组引用,在回调中通过 index - 1 安全访问前驱元素。这避免了手动维护临时变量、闭包状态或额外的预处理步骤,代码更简洁、可读性更高、无副作用。
以下为推荐实现(基于 forEach):
const func1 = () => {
const myArray = ["Harry", "Hermione", "Ron", "Ginny", "Luna"];
myArray.forEach((current, index, arr) => {
func2(current, index, arr);
});
};
const func2 = (current, index, arr) => {
const before = current;
const after = index === 0 ? null : arr[index - 1];
console.log(`before = "${before}", after = "${after}"`);
};
func1();
// 输出:
// before = "Harry", after = "null"
// before = "Hermione", after = "Harry"
// before = "Ron", after = "Hermione"
// before = "Ginny", after = "Ron"
// before = "Luna", after = "Ginny"✅ 关键要点说明:
- forEach 的第三个参数 arr 是对原数组的直接引用,非副本,确保索引访问高效且准确;
- 判断 index === 0 是安全获取前项的前提,避免负索引越界(arr[-1] 返回 undefined,而非 null);
- 若需最终补全 before = null, after = "Luna",可在 func1 中追加一次调用:
// 在 forEach 后添加 if (myArray.length > 0) { func2(null, myArray.length, myArray); // 此时 index 超出范围,仅作标识 }并相应调整 func2:
const func2 = (current, index, arr) => { const before = current; const after = index === 0 ? null : (index <= arr.length ? arr[index - 1] : arr[arr.length - 1]); console.log(`before = ${before === null ? "null" : `"${before}"`}, after = ${after === null ? "null" : `"${after}"`}`); };
⚠️ 注意事项:
- 避免在 func2 内部修改 arr(如 push/splice),否则可能影响后续迭代行为;
- 若数组为空,需单独处理边界情况(myArray.length === 0);
- map() 同样支持三参数签名,但若无需返回新数组,forEach 语义更清晰、性能略优。
该模式本质是将“状态迁移”逻辑从函数外部(易出错的闭包/全局变量)下沉至数据本身(数组 + 索引),符合函数式编程中“数据驱动行为”的设计哲学,兼具健壮性与可测试性。










