添加新对象到数组后旧数据被新值覆盖,求技术排查解决
问题:数组添加新对象后旧元素被新值覆盖
向数组中添加对象后,新对象成功加入,但数组中所有旧元素的值都被新对象覆盖。尝试过直接用索引操作而非push,问题依然存在,已困扰两天。
相关代码
var next if(cart === null){ next = 0 }else { next = cart.length } switch(type){ case 'horizontal': config['0']['type'] = type config['0']['id'] = next config['0'].idImg = selectSvg if(cart === null || cart === undefined || cart.length < 1){ const news = [] news.push(config) setCountCart(news.length) localStorage.setItem('cart-tagstyle', JSON.stringify(news)) setCart(news) }else { const news = [...cart] console.log(news); news.push(config) console.log(news); setCountCart(news.length) localStorage.setItem('cart-tagstyle', JSON.stringify(news)) setCart(news) } break;
问题截图




问题原因
核心问题是数组里的所有元素都引用了同一个config['0']对象:
- 展开运算符
[...cart]只是对数组做浅拷贝,数组内的对象还是原引用,没有生成新的对象实例。 - 每次添加新元素时,你修改的是同一个
config['0']的属性,再把这个对象push到数组里,导致所有数组元素指向同一块内存地址的对象,修改一次就会同步影响所有元素。
解决方案
每次添加新元素时,创建独立的新对象实例,不要复用原config['0']对象,修改后的代码如下:
var next if(cart === null){ next = 0 }else { next = cart.length } switch(type){ case 'horizontal': // 复制原对象属性并生成新对象,避免引用冲突 const newItem = { ...config['0'], type: type, id: next, idImg: selectSvg } if(cart === null || cart === undefined || cart.length < 1){ const news = [newItem] setCountCart(news.length) localStorage.setItem('cart-tagstyle', JSON.stringify(news)) setCart(news) }else { const news = [...cart] news.push(newItem) setCountCart(news.length) localStorage.setItem('cart-tagstyle', JSON.stringify(news)) setCart(news) } break;
说明
- 使用
{...config['0']}创建新对象,复制原对象所有属性后覆盖需要更新的字段,确保每个数组元素都是独立的对象。 - 如果
config['0']包含嵌套对象,需要用深拷贝(比如JSON.parse(JSON.stringify(config['0']))),当前场景下浅拷贝足够解决问题。
内容的提问来源于stack exchange,提问作者Антирка YT
相关产品推荐
相关产品推荐

