我有这个数组:
rows = [ [ 89, 18, 9 ], [ 1903, 3, 4 ], [ 3, 1, 800 ] ];
它应该如下所示:
[ [ 89, 1903, 3 ], [ 18, 3, 1 ], [ 9, 4, 800 ] ]
并且正在运行的代码如下所示:
rows[0].map((_, columnIndex) => rows.map(
row => row[columnIndex])
);
这是如何运作的?
+--- The outter function map gets the first array to loop through the rows
[ 89, 18, 9 ] |
[ 1903, 3, 4 ] |
[ 3, 1, 800 ] v
+--->
|
+- The nested function map is looping through the columns.
The key here is the fixed column using index (column[index])
from the outter function map, so every iteration from the outter
function map will fix the access to that column, i.e -
index = 0 will access the array as follow: array[j][0], array[j+1, 0], ... array[n, 0]
^ ^ ^
这是一种使用直接索引访问来说明正在发生的事情的方法。
var rows = [ [ 89, 18, 9 ], [ 1903, 3, 4 ], [ 3, 1, 800 ] ];
var result = [];
for (var i = 0; i < rows[0].length; i++) {
result[i] = new Array(rows[0].length).fill();
for (var j = 0; j < rows.length; j++) {
result[i][j] = rows[j][i]; // Here is the fixed column access using the outter index i.
}
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
我假设你根本不习惯这里使用的特定语言功能,因此为什么你不能跟踪发生的事情,所以这里是:
Array
。因此嵌套的Array.map
s。map
回调都使用implicit return。这展现了:
rows[0].map((row, index) => {
return rows.map((column) => {
return column[index]
})
})
传递给map
回调的2个参数如下:
element
的论点。map
:当前迭代次数,从0开始;在你的第一个row
中,这是i
的论点。这里的所有都是它的。从那时起,您只需遵循每次迭代时迭代和每个参数的值。