0

I want to modify a two-dimensional array and get a two-dimensional array, but with different contents. In order not to write for a long time, I will show you the codes

const rotateTetromino = () => {
        const rotatedTetromino = [];
        for (let i = 0; i < tetromino.length; i++) {
            rotatedTetromino.push([]);
        }
        let k = 0;
        for (let i = tetromino.length - 1; i >= 0; i--) {
            for (let j = 0; j < tetromino[i].length; j++) {
                rotatedTetromino[j][k] = tetromino[i][j];
            }
            k++;
        }
        return rotatedTetromino;
};

In this version for

let tetromino = [
        [0, 1, 0],
        [0, 1, 0],
        [1, 1, 0],
    ];
 I get  [1, 0, 0],
        [1, 1, 1],
        [0, 0, 0],

and this is right for me, beacouse with that function I can rotate tetromino for tetris game.But when i try the same function whit fill method for rotatetdtetromino, I get wrong array. The function is

const rotateTetromino = () => {
        const rotatedTetromino = new Array(tetromino.length).fill([]);
        let k = 0;
        for (let i = tetromino.length - 1; i >= 0; i--) {
            for (let j = 0; j < tetromino[i].length; j++) {
                rotatedTetromino[j][k] = tetromino[i][j];
            }
            k++;
        }
        return rotatedTetromino;
};

For the same initial rotatedtetromino for loop working in different forms.Why ?

let tetromino = [
        [0, 1, 0],
        [0, 1, 0],
        [1, 1, 0],
    ];
I get   [[0, 1, 0],
         [0, 1, 0],
         [0, 1, 0],]
taginian
  • 3
  • 1

0 Answers0