反转(翻转)二维数组JS

时间:2019-06-18 19:52:08

标签: javascript

我有一个创建/打印二维数组的函数,如下所示:

[0.0,1.0]

如何反转它,以便它像这样创建/打印出一个数组:

["0|0", "0|1", "0|2", "0|3", "0|4"]
["1|0", "1|1", "1|2", "1|3", "1|4"]
["2|0", "2|1", "2|2", "2|3", "2|4"]
["3|0", "3|1", "3|2", "3|3", "3|4"]
["4|0", "4|1", "4|2", "4|3", "4|4"]

以下代码:

["4|0", "4|1", "4|2", "4|3", "4|4"]
["3|0", "3|1", "3|2", "3|3", "3|4"]
["2|0", "2|1", "2|2", "2|3", "2|4"]
["1|0", "1|1", "1|2", "1|3", "1|4"]
["0|0", "0|1", "0|2", "0|3", "0|4"]

3 个答案:

答案 0 :(得分:3)

将数组放入数组并反转。

function createGrid(rowCount, columnCount) {
    for (let x = 0; x < rowCount; x++) {
        for (let y = 0; y < columnCount; y++) {
            cell(x, y);
        }
    }
}

function cell(x, y) {
    grid[x] = grid[x] || [];
    grid[x][y] = x + "|" + y;
}

var grid = [];
createGrid(5, 5);

//Add this code to any code that makes the array of arrays
grid.reverse().forEach(e => console.log(e));

输出:

[ '4|0', '4|1', '4|2', '4|3', '4|4' ]
[ '3|0', '3|1', '3|2', '3|3', '3|4' ]
[ '2|0', '2|1', '2|2', '2|3', '2|4' ]
[ '1|0', '1|1', '1|2', '1|3', '1|4' ]
[ '0|0', '0|1', '0|2', '0|3', '0|4' ]

答案 1 :(得分:2)

您可以将另一个参数传递到cell,该参数将左侧设置为rowCount - 1 - x而不是x

function createGrid(rowCount, columnCount) {
    for (let x = 0; x < rowCount; x++) {
        for (let y = 0; y < columnCount; y++) {
            cell(x, y, rowCount); 
        }
    }
}

function cell(x, y, rowCount) {
    grid[x] = grid[x] || [];
    grid[x][y] = (rowCount - 1 - x) + "|" + y;
}

var grid = [];
createGrid(5, 5);
console.log(grid);

这与您的原始代码相似,但是一种更纯净,更好的方法是使用Array.from一次创建所有数组:

const createGrid = (x, y) => Array.from(
  { length: x },
  (_, i) => (
    Array.from(
      { length: y },
      (_, j) => `${x - 1 - i}|${j}`
    )
  )
);

console.log(createGrid(5, 5));

答案 2 :(得分:1)

这是使用Array.from进行演示的另一种实现方式:

const grid = Array.from({length: 5}, (_, x) => Array.from({length: 5}, (_, y) => `${4-x}|${y}`));

// print result
grid.forEach(row => console.log(...row));