给定一个二维数组(矩阵),如何使用JavaScript进行矩阵的转置。
方法1:
将二维数组存储到变量中。
显示二维数组(矩阵)内容。
调用map()方法,它为数组中的每个元素提供一次回调函数,相对于数组对角线调换数组中元素的位置。
示例:使用array.map()方法
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body style = "text-align:center;"> <p id = "Array" style = "font-size: 16px; font-family: sans-serif; font-weight: bold;"></p> <button onclick = "Run()"> 点击这里</button> <p id = "Array_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"></p> <script> var el_up = document.getElementById("Array"); var el_down = document.getElementById("Array_DOWN"); var array = [ [1, 1, 1], [2, 2, 2], [3, 3, 3], ]; el_up.innerHTML = "[ [ " + array[0] + " ] ], [ [ " + array[1] + " ] ], [ [ " + array[2] + " ] ]"; function transpose(mat) { for (var i = 0; i < mat.length; i++) { for (var j = 0; j < i; j++) { const tmp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = tmp; } } } function Run() { array = array[0].map((col, i) => array.map(row => row[i])); el_down.innerHTML = "[ [ " + array[0] + " ] ], [ [ " + array[1] + " ] ], [ [ " + array[2] + " ] ]"; } </script> </body> </html>
方法2:
将二维数组存储到变量中。
将数组中的每个元素替换为其相对于数组对角线的镜像。
示例:创建一个函数,该函数用镜像替换每个元素以获取数组的转置。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body style = "text-align:center;"> <p id = "Array" style = "font-size: 16px; font-family: sans-serif; font-weight: bold;"></p> <button onclick = "gfg_Run()"> 点击这里</button> <p id = "Array_DOWN" style = "color:red; font-size: 20px; font-weight: bold;"></p> <script> var el_up = document.getElementById("Array"); var el_down = document.getElementById("Array_DOWN"); var array = [ [1, 1, 1], [2, 2, 2], [3, 3, 3], ]; el_up.innerHTML = "[ [ " + array[0] + " ] ], [ [ " + array[1] + " ] ], [ [ " + array[2] + " ] ]"; function transpose(mat) { for (var i = 0; i < mat.length; i++) { for (var j = 0; j < i; j++) { const tmp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = tmp; } } } function gfg_Run() { transpose(array); el_down.innerHTML = "[ [ " + array[0] + " ] ], [ [ " + array[1] + " ] ], [ [ " + array[2] + " ] ]"; } </script> </body> </html>
网友评论文明上网理性发言 已有0人参与
发表评论: