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 />
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".
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With