+ 8
What is the reason that the following code changes more than 1 value?
Beside the reason, can someone give a solution to this issue? https://code.sololearn.com/Wh3a1vC72bLz/?ref=app
3 Réponses
+ 2
So, you create the object "Line".
Let's say it not is in memory at address #0001
You then create Array, and you fill every record with the object "Line".
In every record of "Array", you do NOT have different "Line" objects.
In fact, image the content of every "Array" record, as a link to #0001, instead as a "Line" object.
When you change the value in 2,2, you are basically accessing and editing the content of #0001
So, the value will change for every thing that refers to that address.
(Basically, every record of "Array")
- - - I try to put that in another way - - -
Every record of "Array", point toward the same "Line" object in memory.
the object LINE is the same in all the 4 record of "Array".
They aren't 4 different LINE objects.
(I don't know if I'm clear. If not, I'll try to explain in a different way. Sadly my english kinda sucks.)
:D
Try to create the matrix using another way, and you'll see that your function will work:
var array = [];
for(var i=0; i<4; i++) {
array[i] = [];
for(var j=0; j<4; j++) {
array[i][j] = false; }
}
function change(i, j) {
array[i][j] = !array[i][j];
return array;
}
console.log(change(2, 2));
+ 6
Thank you for your detailed answer!
0
You're welcome. :)