为什么在动态填充对象时所有对象属性的值都在变化? Java脚本

时间:2018-07-20 22:40:31

标签: javascript object frontend

注意: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"}
        }
    }

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

1 个答案:

答案 0 :(得分:1)

除非您使用某种深度复制,否则您只是将引用复制到原始对象。参见What is the most efficient way to deep clone an object in JavaScript?