-2

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}

why its changing the array1 object while i added a key value pair for array2?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Linson
  • 655
  • 1
  • 7
  • 21
  • 1
    Well obviously you're not making a copy. And you're not using an Array properly. –  Nov 04 '14 at 21:21
  • Duplicate question of many others asked before. I will go find one of those dups. – jfriend00 Nov 04 '14 at 21:22
  • @jfriend00: While the answer to the referenced question also answers this question, I do not think of this question as a duplicate of that one. Not that I doubt that this is likely a duplicate of **something**. – Scott Sauyet Nov 04 '14 at 21:31
  • Here's one that deals with the expectation that an object assignment makes a copy: http://stackoverflow.com/questions/24586423/javascript-why-assigning-a-variable-to-an-object –  Nov 04 '14 at 21:34
  • @squint - And your reference is actually marked as a dup of this one: http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language. There are many, many to choose from. – jfriend00 Nov 04 '14 at 22:30
  • @jfriend00: Yeah, I know. I just wanted to provide one that was specifically trying to make a copy via assignment. Doesn't matter. Like you said, there are many. –  Nov 04 '14 at 22:33

3 Answers3

1

When you do something like array2 = array1; you are just setting array2 as a reference to array1. To make a copy of array1 you need to do array2 = array1.slice();

Furthermore, you can not set Array elements with array1.value1 ='1';. What you have done there is convert your array to an Object. So what you really should be doing is:

var array1 = [];
var array2 = [];
array1[0] = 1;
array2 = array1.slice();
array2[1] = 2;
Warren R.
  • 497
  • 3
  • 12
1

By doing array2 = array1; you are assigning the array1 object to array2 variable. So modifying array2 will modify the object associated i.e. array1

Yash
  • 182
  • 1
  • 4
0

Because you pass by reference array1 to array2. You need to do a copy like:

array2 = new Array(array1);
AlexL
  • 1,699
  • 12
  • 20