当前位置:网站首页>JS中为对象数组添加新对象结果导致数组中已存在的对象也修改了
JS中为对象数组添加新对象结果导致数组中已存在的对象也修改了
2022-07-28 16:26:00 【Mr_Bobcp】
问题描述
为对象数组添加新对象结果导致数组中已存在的对象也改变了
我需要将一个空数组中存放已有的某个对象,这个对象是复用的,结果每次执行添加后所有对象都成为了最后添加的那个。
this.ObjList.push(this.Obj);
问题分析
因为数组是引用传递而不是值传递,指向的是同一个内存地址 ,所以赋值给数组里的对象其实一直都是同一个地址里存的同一个数组 ,所以最后一次输入的值会将每个引用的值都修改。
解决方法
先先将需要操作的Obj对象转换成字符串,然后再转换成对象这样就会新分配一块内存新创建一个对象。
this.ObjList.push((JSON.parse(JSON.stringify(this.Obj))));
边栏推荐
猜你喜欢

How to protect image security during construction

Connection design and test platform -- Summary of SystemVerilog interface knowledge points

wpf命令按钮透明样式

The actual combat of the beego framework of goweb development: Section III program execution process analysis

Firewalld防护墙

net框架

Verilog 每日一题 (VL28 加减计数器)

Encrypt the video and upload it to OSS to achieve high concurrent access

MySQL详细学习教程(建议收藏)

Goweb开发之Beego框架实战:第四节 数据库配置及连接
随机推荐
MySQL detailed learning tutorial (recommended Collection)
Basic principle of asynchronous FIFO (simple implementation based on Verilog)
在PDF中插入文本水印
Verilog 每日一题(VL2 异步复位的串联T触发器--牛客网)
2021年4月份自考
Janus series article 3 API usage guide videoroom creating a new video room
Redis源码剖析,狠狠地拿捏了,赶紧码住
Using SQL server agent job to restore the database regularly
Visual Studio 2012/2015发布Web应用连同.cs源码一起发布
Master the key points of JVM interview
Differences between CNSA and CASC and CASIC
The practice of beego framework developed by goweb: Section 4 database configuration and connection
The practice of the beego framework of goweb development: Section II project initialization configuration
Use of influxdb2
Vscode uses eslint prettier to format code automatically
[atlas] atlas compilation error sorting (all)
AMQP协议详解
[CDH] configure CDH components through clouderamanager and collect JMX information with Prometheus monitoring
2022 Niuke multi school second CDE
Self study examination in April 2021