-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?

6
  • 1
    Well obviously you're not making a copy. And you're not using an Array properly. Commented Nov 4, 2014 at 21:21
  • Duplicate question of many others asked before. I will go find one of those dups. Commented Nov 4, 2014 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. Commented Nov 4, 2014 at 21:31
  • Here's one that deals with the expectation that an object assignment makes a copy: stackoverflow.com/questions/24586423/… Commented Nov 4, 2014 at 21:34
  • @squint - And your reference is actually marked as a dup of this one: stackoverflow.com/questions/518000/…. There are many, many to choose from. Commented Nov 4, 2014 at 22:30

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

array2 = new Array(array1);

3 Comments

This actually does not work. It creates an array with array1 as an item in the array.
I don't know. I countered it, though. :-)
@ScottSauyet: So did I. Two people now upvoted it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.