Javascript - 将列转换为行

时间:2017-10-29 23:08:13

标签: javascript arrays

相对较新的JS,试图理解这个代码,它接受一个数组并将其列转换为数组。

grid= 
[[".",".",".","1","4",".",".","2","."], 
[".",".","6",".",".",".",".",".","."], 
[".",".",".",".",".",".",".",".","."], 
[".",".","1",".",".",".",".",".","."], 
[".","6","7",".",".",".",".",".","9"], 
[".",".",".",".",".",".","8","1","."], 
[".","3",".",".",".",".",".",".","6"], 
[".",".",".",".",".","7",".",".","."], 
[".",".",".","5",".",".",".","7","."]]

//Turn columns into rows
var transpose = grid =>
    grid[0].map(
        (_,c) => grid.map(
            row => row[c]
        )
    )

这看起来如何使用常规功能?

1 个答案:

答案 0 :(得分:1)

var transpose = grid =>     // defining `transpose` as function with parameter `grid`, returning the following expression
    grid[0].map(            // return values from first row mapped via following function
        (_,c) => grid.map(  // using second parameter which is an index to do column mapping
            row => row[c]   // returning the value with index of row but from column
        )
    )

因此,如果没有这个ES6 map函数,它将是2个嵌套循环:



var grid = 
  [[".",".",".","1","4",".",".","2","."], 
  [".",".","6",".",".",".",".",".","."], 
  [".",".",".",".",".",".",".",".","."], 
  [".",".","1",".",".",".",".",".","."], 
  [".","6","7",".",".",".",".",".","9"], 
  [".",".",".",".",".",".","8","1","."], 
  [".","3",".",".",".",".",".",".","6"], 
  [".",".",".",".",".","7",".",".","."], 
  [".",".",".","5",".",".",".","7","."]];

function transpose(grid) {
    var ret = [];
    for (var i = 0; i < grid[0].length; i++) {
        ret[i] = [];
        for (var j = 0; j < grid.length; j++) {
            ret[i][j] = grid[j][i];
        }
    }

    return ret;
}

// use map for pretty printing the matrix
console.log(grid.map(row => row.join(' ')));
console.log(transpose(grid).map(row => row.join(' ')));
&#13;
&#13;
&#13;