I am working on a small personal project and I ran over something that I don't understand and I am hoping if someone can explain it to me. One of the methods in my module is SaveSet() which takes an array and adds it to a different array as an element so it become two dimensional array here is the code for the SaveSet():
function SaveSet() {
anim.push(set)
}
When I run this code I expect it to take whatever is in the set array and adds it to the anim array as an element like this.
Set = [1,2,3,4]
SaveSet()
Set = [3,4,5,6]
SaveSet()
and I should end up with something like this:
[
[1,2,3,4]
[3,4,5,6]
]
However, my SaveSet() is modifying the existing one and adding a new one so I end up with something like this
[
[1,2,3,4,3,4,5,6]
[1,2,3,4,3,4,5,6]
]
I found a work around it by changing my SaveSet() to this:
function SaveSet() {
let temp = JSON.stringify(set)
anim.push(JSON.parse(temp));
}
However, I still can't understand why anim.push is modifying the existing one as well. This is the full code incase if anyone wants to look at it. As I said this a personal quick project so the quality of the code and design are really low. https://codepen.io/anon/pen/oJZeJy?editors=1111
function saveSet( ary, addition ) { ary.push( addition); return ary; }will go a long way with avoiding such issues in code logic, since it requires you to explicitly send it the array to change and the array to add. You'll have to read a bit about object references and such if you want a thorough explanation.