Javascript 数组在 for 循环中不会改变

Javascript array won't change inside of for loop

我正在尝试旋转 javascript

中的二维数组

用于切换值的 forloop 外部代码有效,但是当我尝试在 for 循环内执行此操作时,变量没有改变

我认为这是某种参考问题,我进行了搜索,但找不到该问题的解决方案

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]);
        }
    }

尝试在您的 for 循环中添加“let”关键字,这可能是一个提升问题;

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]);
        }
    }

我觉得在旧数组的基础上建一个新数组会更容易

下面的代码是在原数组的基础上反向构建的新数组

arr = [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]];

console.log(JSON.stringify(Rotate2D(arr)));

function Rotate2D(array) {
  //Create a new empty array with the same size as the original one.
  let returnArr = [...Array(array.length)].map(e => Array(array[0].length));
  let maxIndexI = array.length - 1;
  let maxIndexJ = array[0].length - 1;

  //Fill the return array rotated
  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array[0].length; j++) {
      returnArr[maxIndexI - i][maxIndexJ - j] = array[i][j]
    }
  }
  return returnArr;
}