简体   繁体   English

给它赋值时 javascript 对象的奇怪行为

[英]weird behavior of javascript objects when assigning a value to it

I want to understand this concept which confuses me.我想理解这个让我困惑的概念。

suppose I have the below logic:假设我有以下逻辑:

function test(){
    var jsonObj_1 = {};
    var jsonObj_2 = {};
    
    jsonObj_2 = jsonObj_1;
    jsonObj_2.myKey = 3;

    console.log(jsonObj_2) // result => {myKey:3}
    console.log(jsonObj_1) // result => {myKey:3}

}

my question is why jsonObj_1 is equal to {myKey:3} when it's never get assigned?!我的问题是为什么jsonObj_1永远不会被分配时等于{myKey:3} ?!

you are assigning the ref of jsonObj_1 in jsonObj_2.您正在 jsonObj_2 中分配 jsonObj_1 的引用。 In simple words the address of the first variable.简单来说就是第一个变量的地址。 I would suggest you to read some docs on call by reference and call by value.我建议您通过引用和按值调用来阅读一些随叫随到的文档。

What you will need is Object.assign你需要的是Object.assign

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

Example here: https://googlechrome.github.io/samples/object-assign-es6/这里的例子: https : //googlechrome.github.io/samples/object-assign-es6/

When the non-primitive variables are assigned using "=", the reference will also be copied.当使用“=”分配非原始变量时,引用也将被复制。 This may lead to the mutation for all the variables that a particular object is assigned to.这可能会导致分配给特定对象的所有变量发生突变。

Try the following.请尝试以下操作。

You can use JSON.stringify to convert it to string and then parse into JSON.parse.您可以使用 JSON.stringify 将其转换为字符串,然后解析为 JSON.parse。

jsonObj_2= JSON.parse(JSON.stringify(jsonObj_1));

You can use spread operator.您可以使用扩展运算符。

jsonObj_2 = {...jsonObj_1}

JavaScript Objects are Mutable. JavaScript 对象是可变的。 They are addressed by reference, not by value.它们是通过引用而不是值来寻址的。

If jsonObj_1 is an object, the following statement will not create a copy of jsonObj_1:如果 jsonObj_1 是一个对象,以下语句不会创建 jsonObj_1 的副本:

 var jsonObj_2 = jsonObj_1 ; // This will not create a copy of jsonObj_1.

The object jsonObj_2 is not a copy of jsonObj_1 .对象 jsonObj_2 不是 jsonObj_1 的副本。 It is jsonObj_1.它是 jsonObj_1。 Both jsonObj_2 and jsonObj_1 are the same object. jsonObj_2 和 jsonObj_1 都是同一个对象。

Any changes to jsonObj_2 will also change jsonObj_1, because jsonObj_2 and jsonObj_1 are the same object.对 jsonObj_2 的任何更改也会更改 jsonObj_1,因为 jsonObj_2 和 jsonObj_1 是同一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM