二维数组上的Javascript映射
我有这个阵列:二维数组上的Javascript映射,javascript,Javascript,我有这个阵列: 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]) ); 这是如何工作的?我假设您根本不习
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])
);
这是如何工作的?我假设您根本不习惯这里使用的特定语言功能,因此您无法了解正在发生的事情,因此:
- 您的结构是嵌套的
。因此嵌套的数组
sArray.map
回调都使用了map
rows[0].map((row, index) => {
return rows.map((column) => {
return column[index]
})
})
传递给map
回调的两个参数如下:
:当前迭代的数组元素;在第一个元素
中,这是map
参数行
:当前迭代次数,从0开始;在第一个i
中,这是map
参数index
+--- 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行=[[89,18,9],[1903,3,4],[3,1800];
var结果=[];
对于(var i=0;i<行[0]。长度;i++){
结果[i]=新数组(行[0]。长度).fill();
对于(var j=0;j
.as控制台包装{max height:100%!important;top:0;}
迭代器方法(如map
,forEach
,filter
…)处理数组2d,因为每个元素都是1d数组
例如:
arr= [[1,0,0],
[0,1,0],
[0,0,1]]
arr.map( (item)=> {
item.forEach( (element)=> {
//...
//...
})
})
第一个迭代器(map
)取本例中arr数组的第一行[1,0,0]
第二个迭代器获取arr的第二行,即[0,1,0]
将其保存在item中,依此类推
在采用实数的嵌套循环(foreach
)中,如0
或1
。这里的代码可以处理它。2d标记的描述是2d计算机图形学是基于计算机的数字图像生成,主要来自二维模型。
-完全不是你所说的。你正在转换你的数据结构,因为它是方形的,所以只能与代码一起工作。不管怎样,也许你可以解释一下哪些部分让你困惑?您检查了map
的功能了吗?我了解map的功能,但不了解第二个链式映射如何到达正确的数组元素。你能给我解释一下吗?@Jeroen不一定是方的。它可以是任何矩形阵列。只是变量的名称有误导性。我宁愿写行[0].map(u,columnIndex)=>rows.map(row=>row[columnIndex])
。我只是在写我自己几乎相同的答案+1.我的for循环与你的略有不同:for(var i=0;i
@Zze是的,它是类似的!