JavaScript数组分配问题 [英] JavaScript array assign issue
本文介绍了JavaScript数组分配问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚创建了两个数组,并向其中一个数组分配了一个插入的键值对.然后我分配或复制一个数组到其他.之后,我在第二个数组中添加了另一个键值对,但它也反映了原始数组.例如.
I just created two arrays and assigned a inserted a key value pair to one of the array. Then i assigned or copy an array to other. After that i added another key value pair to second array, but it reflects to the original array also. For example.
var array1 =[];
var array2 =[];
array1.value1 ='1';
array2 = array1;
array2.value2 ='2';
console.log(array1); // it prints {value1:1, value2:2}
为什么在我为array2添加键值对的同时改变了array1对象?
why its changing the array1 object while i added a key value pair for array2?
推荐答案
通过执行array2 = array1;
,您正在将array1对象分配给array2变量.因此,修改array2将修改关联的对象,即array1
By doing array2 = array1;
you are assigning the array1 object to array2 variable. So modifying array2 will modify the object associated i.e. array1
这篇关于JavaScript数组分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文