Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "a.push(b)" change "b" in my example code?

I'm trying to push a value to an array, but this adds the value to both arrays a and b. How can I make sure that the b array is not modified?

var a=[[1]];
var b= [2];
document.getElementById("1").innerHTML="a[1] "+a[1];
document.getElementById("2").innerHTML="b "+b;

a.push(b);
document.getElementById("3").innerHTML="a[1] "+a[1];
document.getElementById("4").innerHTML="b "+b;

a[1].push([3]);
document.getElementById("5").innerHTML="a[1] "+a[1];
document.getElementById("6").innerHTML="b "+b+" < why did this value changed?";
<div id="1"></div>
<div id="2"></div><br />
<div id="3"></div>
<div id="4"></div><br />
<div id="5"></div>
<div id="6"></div><br />
like image 518
user2998225 Avatar asked Sep 09 '18 16:09

user2998225


People also ask

What does a B mean in JavaScript?

This is important because the "binary +" operator does different things depending on the type of its operands: if a was a string, a + b would mean "append two strings together" rather than "sum two numbers".

How do you add an object to an array?

The push() function is a built-in array method of JavaScript. It is used to add the objects or elements in the array. This method adds the elements at the end of the array. "Note that any number of elements can be added using the push() method in an array."


1 Answers

Just copy the original array using slice() instead of passing the reference. Array.slice() would return a new array instance copied from the original array.

When you are doing a.push(b); you have inserted the reference of the array b into a.

Now when you do a[1].push([3]); you actually insert the array [3] into the b reference which is at index 1 of array a. That is why you are seeing a changed value.

var a=[[1]];
var b= [2];
document.getElementById("1").innerHTML="a[1] "+a[1];
document.getElementById("2").innerHTML="b "+b;

a.push(b.slice());
document.getElementById("3").innerHTML="a[1] "+a[1];
document.getElementById("4").innerHTML="b "+b;

a[1].push([3]);
document.getElementById("5").innerHTML="a[1] "+a[1];
document.getElementById("6").innerHTML="b "+b+" < why did this value changed?";
<div id="1"></div>
<div id="2"></div><br />
<div id="3"></div>
<div id="4"></div><br />
<div id="5"></div>
<div id="6"></div><br />

Note:

For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array do not affect the other array.

like image 111
Fullstack Guy Avatar answered Nov 14 '22 21:11

Fullstack Guy