'Javascript array won't change inside of for loop
I am trying to rotate a 2dimensional array in javascript
the code outside the forloop to switch the values works but when i try to do that inside the for loop the variables are not changing
i think it is some sort of reference problem and i searched for that but i can't find a solution to this problem
temp = tempboard[0][1];
console.log("unchanged:"+tempboard[0][1]+""+tempboard[6][1]);
tempboard[0][1] = tempboard[6][1];
tempboard[6][1] = temp;
console.log("changed:"+tempboard[0][1]+""+tempboard[6][1]);
for(i = 0; i < board.length; i++){
for(j = 0; j < board[0].length; j++){
/*a = tempboard[i][j];
b = tempboard[j][i];
temp = a;
a = b;
b = temp;
console.log(a+" "+b);*/
temp = tempboard[i][j];
console.log("unchanged:"+tempboard[i][j]+""+tempboard[j][i]);
tempboard[i][j] = tempboard[j][i];
tempboard[j][i] = temp;
console.log("changed:"+tempboard[j][i]+""+tempboard[i][j]);
}
}
Solution 1:[1]
Try adding "let" keyword to your for loop, it could be an hoisting issue;
for(let i = 0; i < board.length; i++){
for(let j = 0; j < board[0].length; j++){
/*a = tempboard[i][j];
b = tempboard[j][i];
temp = a;
a = b;
b = temp;
console.log(a+" "+b);*/
temp = tempboard[i][j];
console.log("unchanged:"+tempboard[i][j]+""+tempboard[j][i]);
tempboard[i][j] = tempboard[j][i];
tempboard[j][i] = temp;
console.log("changed:"+tempboard[j][i]+""+tempboard[i][j]);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nekan123 |
