修改 JavaScript 对象的副本会导致原始对象发生变化

2022-01-20 00:00:00 复制 object 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 中,对象是通过引用传递和分配的(更准确地说是引用的值),所以 tempMyObjmyObj 都是对同一个对象的引用.

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);

请参阅此处和这里

相关文章