Modifying a copy of a JavaScript object is causing the original object to change(修改 JavaScript 对象的副本会导致原始对象发生变化)
问题描述
我正在将 objA
复制到 objB
const objA = { prop: 1 },
const objB = objA;
objB.prop = 2;
console.log(objA.prop); // logs 2 instead of 1
数组也有同样的问题
const arrA = [1, 2, 3],
const arrB = arrA;
arrB.push(4);
console.log(arrA.length); // `arrA` has 4 elements instead of 3.
推荐答案
很明显,您对语句 var tempMyObj = myObj;
的作用有一些误解.
It is clear that you have some misconceptions of what the statement var tempMyObj = myObj;
does.
在 JavaScript 中,对象是通过引用传递和分配的(更准确地说是引用的值),所以 tempMyObj
和 myObj
都是对同一个对象的引用.
In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so tempMyObj
and myObj
are both references to the same object.
这是一个简化的插图,可以帮助您直观地了解正在发生的事情
Here is a simplified illustration that may help you visualize what is happening
// [Object1]<--------- myObj
var tempMyObj = myObj;
// [Object1]<--------- myObj
// ^
// |
// ----------- tempMyObj
正如你在赋值后看到的,两个引用都指向同一个对象.
As you can see after the assignment, both references are pointing to the same object.
如果您需要修改一个而不是另一个,则需要创建一个副本.
You need to create a copy if you need to modify one and not the other.
// [Object1]<--------- myObj
const tempMyObj = Object.assign({}, myObj);
// [Object1]<--------- myObj
// [Object2]<--------- tempMyObj
旧答案:
以下是创建对象副本的其他几种方法
Here are a couple of other ways of creating a copy of an object
既然你已经在使用 jQuery:
Since you are already using jQuery:
var newObject = jQuery.extend(true, {}, myObj);
使用原生 JavaScript
With vanilla JavaScript
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var newObject = clone(myObj);
请参阅此处和这里
这篇关于修改 JavaScript 对象的副本会导致原始对象发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:修改 JavaScript 对象的副本会导致原始对象发生变化


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01