0

I am not sure what's going on with this, probably I am doing something wrong, but to be honest, I cannot see what's the point. Just take a look at this code and see what happens:

var object = {
  one: "one",
  two: "two"
};

var object2 = {}

object2 = object;

object["three"] = "what?"

console.log(object2);

The output for the object2 should be {one: "one", "two": two"}, however it returns {one: "one", "two": two", "three": "what?"}

So why is this happening? I am not modifying object2, but it gets updated after the push of new value. How can I solve this? I just want to keep the object2 like before. Thanks

4

2 回答 2

4

object2 引用对象(指向内存中的相同引用)

我假设你想创建 object2 是第一个的副本,你可以这样做:

var obj2 = Object.assign({}, object);

或者

var obj2 = {...object}

你可以检查Object assign MDN,或者只是谷歌关于传播运算符语法

于 2018-09-30T20:46:19.937 回答
-1

当您将对象分配给 object2 时,它是对 object2 的引用。因此,当您添加“三个”时:“什么?” 对象和打印对象2,它将是相同的。

于 2018-09-30T20:47:28.020 回答