复制备份对象似乎是反向复制

问题描述 投票:0回答:1

终于有了一个可以用小代码重现的问题。结果在控制台中。片段背景是否被视为与 Global 相同?

将数组复制到对象中(从 [] 格式)可以工作(第一个示例),但是(第二个示例)在其中设置数组的一个元素,然后将其复制到另一个对象属性似乎以相反方向复制该属性。

var obj = {   //obj should be global, and the code below in a function,
    var1: [],
    var2: []  //But still same failure
}

obj.var1 = [1, 10, 1]; //first values
obj.var2 = obj.var1; //save backup globally in var2 between function calls
// ...
obj.var1 = [0, 2, 0]; //a new function call with new value in val1
// ...
obj.var1 = obj.var2; //and then overwrite and restore first values
console.log("1. This works: var1 = " + obj.var1 + ", var2 = " + obj.var2);
// both are [1,10,1] as expected

obj.var1[1] = 99;  //another new value, in one array index
// ...
obj.var1 = obj.var2; //and then restore first values again
console.log("2. Appears to copy the reverse  direction:\nvar1 = " + obj.var1 + ",  var2 = " + obj.var2);

//2.expects both var1 and var2 to be [1, 10, 1] but Both become [1, 99, 1] ?

javascript javascript-objects
1个回答
0
投票

Javascript中的对象和数组都是引用类型。当您执行

obj.var1 = obj.var2;
时,它会复制对
var1
的引用,并且
var1
var2
都指向同一对象。当您更新其中任何一个时,两者都会更新。为了避免这种情况,你应该进行深复制。将数组的各个元素复制到
var1
。参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects#comparing_objects

© www.soinside.com 2019 - 2024. All rights reserved.