javascript object reference and assignment

javascript object reference and assignment

 

javascript object reference and assignment

<script type="text/javascript">

//Example 1: reference

var myArrayRef = new Array(0,1,2); //Create an array object

var mySeconArrayRef = myArrayRef; // Object copy.

myArrayRef[0] = 100; // modify element value

alert(mySeconArrayRef[0]);

/**

* Output 100; anyone who has learned other languages ​​should know that the output should be 0. Why is the output 100?

* In the above program, by copying the myArrayRef object to mySeconArrayRef, there are 2 independent objects with the same initial value

* Because it is independent, why does modifying myArrayRef affect another object? Everyone knows that modifying one will only happen when they refer to the same object.

* Affects the other one. But in the value of the object myArrayRef created in the javascript language, the reference to the object (that is, an address) is saved.

* That is, what I generated with new Array is stored in memory and new Array tells myArrayRef where it is, and myArrayRef tells mySeconArrayRef the address.

* Both of them point to the address of the object generated by the new Array instead of saving the object in myArrayRef, so when one of them is used to modify the value, it is the object of the same reference to which they are modified.

*/

alert(mySeconArrayRef[0] );

//Example 2: Assignment

var myVa = 'ABC'; //Assign the value of ABC to myVa

var myVb = myVa; // assign myVa to myVb

myVa = 'DEF'; //modify myVa

/**

* The output is: ABC. Because the value is stored in the variable instead of the reference address, the two of them are relatively independent.

*/

alert(myVb);

</script>

如果真要复制对象互不影响,则要通过转换赋值或者遍历key:value来复制你中的方法和属性。

注意:对象的子对象也是引用,所以遍历赋值的时候要判断,子元素是否是对象,如果子元素是对象,则继续对子元素进行遍历赋值。
转换赋值方式:

复制代码
var data = {a:1,b:2,c:3,d:[0,1,2,3]};
var str = JSON.stringify(data);
var data1 = $.parseJSON(str); //$为jQuery对象需要引入jQuery包
data1["e"] = 4;
data1["d"][0] = 11;
console.log(data);
console.log(data1);
复制代码

输出结果:
{a1b2c3d: [0,1,2,3]}
{a1b2c3d: [11,1,2,3], e: 4}

相互没有影响

 

当对象引用做为函数参数传递时候,依然会相互影响,切记,如下示例:

 

 

复制代码
var data = {a:1,b:2,c:3,d:{q:4,w:5,e:6}};
var data1 = data;
function con(data2){
data2["r"] = 5;
console.log(JSON.stringify(data2));
}
con(data1);
console.log(JSON.stringify(data));
复制代码

输出结果:

{"a":1,"b":2,"c":3,"d":{"q":4,"w":5,"e":6},"r":5}
{"a":1,"b":2,"c":3,"d":{"q":4,"w":5,"e":6},"r":5}
 
对象引用赋值后,如果将对象置空,相互间是不受影响的,如下:
var arr = {"a":"1","b":"2"};
var arr1 = arr;
arr = {};
arr["a"] = 2;
console.log(arr1);
console.log(arr);

输出结果:{"a":"1","b":"2"},{"a":2}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326709974&siteId=291194637