首页 > 解决方案 > 为什么在动态填充对象时所有对象属性的值都在变化?Javascript

问题描述

注意:subObj, subObj2, subObj3, subObj4 都是对象{}

这是代码:

for (var key in subObj) {
  if (subObj.hasOwnProperty(key)) {
    subObj2 = subObj[key];

    subObj3["player"] = subObj2["player"];
    subObj3["bodypart"] = subObj2["bodypart"];
    subObj3["type"] = subObj2["type"];
    subObj3["result"] = subObj2["result"];
    aux = subObj2["zone"];

    //WARNING: here is the problem. All object content (except keys) are being set to subObj3
    console.log(subObj4); 

    //initialize > important! (this creates new properties in object)
    if (!subObj4.hasOwnProperty(aux)) {
      subObj4[aux] = {};
    }
    if (!subObj4[aux].hasOwnProperty(key)) {
      subObj4[aux][key] = {};
    }

    //store
    subObj4[aux][key] = subObj3;

    console.log("aux = ", aux, " key = ", key);
    console.log(subObj3);
    console.log(subObj4);
  } //endif
} //endfor 

控制台日志

电流输出:

第一个循环:

//log of "aux" and "key"
aux = e3c , key = 1

//log of "subObj3"
    {player: "john", bodypart: "h", type: "open_t", result: "correct"}

//log of "subObj4"
    {e3c:{ 
            1:{player: "john", bodypart: "h", type: "open_t", result: "correct"}
        }
    }

第二个循环:

//log of "aux" and "key"
aux = e3c , key = 4

//log of "subObj3"
    {player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}

//log of "subObj4"
    {e3c:{ 
            1:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
            4:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
        }
    }

预期输出:

//log of "subObj4"
    {e3c:{ 
            1:{player: "john", bodypart: "h", type: "open_t", result: "correct"}
            4:{player: "robert", bodypart: "lf", type: "open_t", result: "incorrect"}
        }
    }

经过更多调试后,我发现对象正在更改其值(它在代码中用“警告”注释)。在那一行中,所有对象值都发生了变化

标签: javascriptobjectfrontend

解决方案


除非您使用某种深拷贝,否则您只是在复制对原始对象的引用。请参阅在 JavaScript 中深度克隆对象的最有效方法是什么?


推荐阅读