You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用splice复制数组对象后索引重置异常问题求助

问题分析与解决方案:数组对象复制时的索引异常问题

问题根源

你遇到的问题核心是对象浅拷贝导致的引用共享,再加上一处代码笔误:

  1. 对象引用未切断:const newFruit = fruits[index];只是把原数组里的对象引用赋值给了newFruit,并没有创建新的水果对象。插入数组后,新数组里会有两个元素指向同一个内存地址的对象。后续循环修改index时,最后一次对这个共享对象的赋值会覆盖之前的结果——比如循环到i=2时修改的是这个共享对象的index,所以原位置的orange也会同步变成2。
  2. 返回变量错误:函数最后return newArray;是笔误,应该返回newList,否则会直接报错,你能得到结果应该是测试时临时修正过,但这个问题需要注意。

修正后的代码

const fruits = [
  {"name": "banana", "index": 0},
  {"name": "orange", "index": 1},
  {"name": "lemon", "index": 2}
];

const duplicate = (index) => { 
  const newList = [...fruits];
  // 拷贝原对象,切断引用(单层对象用展开语法足够)
  const newFruit = {...fruits[index]};
  newList.splice(index + 1, 0, newFruit);

  for(let i = 0; i < newList.length; i++) {
    newList[i].index = i;
  };

  return newList;
};

// 测试调用
console.log(duplicate(1));

修正说明

  • 用{...fruits[index]}创建原对象的浅拷贝(针对单层结构的对象完全够用),如果是嵌套对象,可以用JSON.parse(JSON.stringify(fruits[index]))或者其他深拷贝工具方法。
  • 修正返回变量为newList,确保函数返回正确的新数组。

运行结果

调用duplicate(1)后会得到预期结果:

[
  {"name": "banana", "index": 0},
  {"name": "orange", "index": 1},
  {"name": "orange", "index": 2},
  {"name": "lemon", "index": 3}
]

内容的提问来源于stack exchange,提问作者gcbox999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 01:45:46