+ 1

can anyone help me find the bug?

When I run this part of the code, both originalArray and gridArray both output nothing, even though I defined it above, and still ran function add console.log(originalArray) console.log(gridArray) if(originalArray !== gridArray){ console.log("hi"); add(1); And this is above, where I defined the 2 variables: function move(dir) { var originalArray = [gridArray]; //I had to make originalArray a array for the code to work //may change gridArray ... console.log(originalArray) console.log(gridArray) if(originalArray !== gridArray){ console.log("hi"); add(1); } } And also, if you do: console.log(originalArray + "") console.log(gridArray + "") if(originalArray !== gridArray){ console.log("hi"); add(1); } } the originalArray and gridArray will output and shows that originalArray is still changing itself to gridArray even though I did not set it so originalArray would change, and then it will also still broadcast "hi" and run the function add, like if the if is not there somehow. here's the link to my code: https://code.sololearn.com/WZPrRV1jhl76/#html

13th Oct 2020, 2:31 PM
EpsilAnt
EpsilAnt - avatar
1 Antwort
+ 2
In the line where you're comparing originalArray and gridArray for changes to determine if a new item should be added. This comparison (originalArray !== gridArray) is comparing object references, not their content. As a result, even if the content of the arrays changes, this condition might not be met because they are different object references. To compare the content of two arrays, you should use a deep equality check.
15th Sep 2023, 5:09 PM
JAY
JAY - avatar