gpt4 book ai didi

Javascript - 将列转换为行

转载 作者:行者123 更新时间:2023-12-03 03:09:36 25 4
gpt4 key购买 nike

对于 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]
)
)

使用常规函数会是什么样子?

最佳答案

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(' ')));

关于Javascript - 将列转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47006191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com