I've been working on a web project, and I'm having an issue with assigning a window variable to another variable in Javascript.
For example, I have a function that generates a random code:
window.onload=function(){
...
window.c=genCode(); //Gets an array with 4 strings like ['g', 'r', 'p', 'b'] (first letter of colors of the rainbow)
...
}
Then later on in the program, I have a test that will use the data in a variable, and minipulate the new variable
var guess=function(){
...
let tempC=window.c;
...
for(let i=0;i<4;i++){
...
tempC[i]='n';
...
}
}
The local variable tempC gets changed, but so does window.c.
My workaround is to just have a function that returns the variable.
var retCode=function(){
return window.c;
}
This works, but why does this happen? When you assign data to a variable, I thought it should only modify the specified variable and not the one it gets the data from. Is this just a JavaScript quirk? Does it have to do something with how window works?
let tempC = JSON.parse(JSON.stringify(window.c));.. Or really, just look at this: stackoverflow.com/questions/9885821/…window.candtempCpoint to the same array in memory