JavaScript 对二维数组进行映射

6

我有这个数组:

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])
        );

这是如何工作的呢?

1
2d标签的描述为“2D计算机图形是基于计算机生成数字图像的过程,主要来自二维模型。” - 这完全不是你正在谈论的内容。 - vityavv
1
你正在对数据结构进行转置,这只能在代码是“方形”的情况下起作用。无论如何,也许你可以解释一下哪些部分让你困惑?你已经查过map的作用了吗? - Jeroen
1
我理解 map 的作用,但我不明白第二个链式 map 如何获取正确的数组元素。你能解释一下吗? - skinnyBug
@Jeroen 不一定是正方形的。它可以是任何矩形数组。只是变量的名称有误导性。我宁愿写 rows[0].map((_, columnIndex) => rows.map(row => row[columnIndex])) - Aadit M Shah
3个回答

8
我假设你只是不熟悉这里使用的特定语言功能,因此无法理解正在发生的事情,所以在这里解释一下:
  • 你的结构是一个嵌套的Array。因此有嵌套的Array.map

  • 两个map回调都使用了隐式返回

展开后如下:

rows[0].map((row, index) => {
  return rows.map((column) => {
    return column[index]
  })
})

map回调函数接受两个参数:

  • element: 目前迭代的数组元素;在你的第一个map中,这是row参数。
  • i: 当前迭代次数,从0开始;在你的第一个map中,这是index参数。

就是这些。之后你只需按照每次迭代和每个参数的值进行操作。


2
                  +--- 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]
                                                         ^              ^                ^

This is an approach to illustrate what's happening using direct index accesses.

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; }


刚刚在写几乎一模一样的答案。+1。不过我的for循环和你的略有不同:for(var i = 0; i < rows[0].length; i++){ result.push([]); for(var j = 0; j < rows.length; j++){ result[result.length-1].push(rows[j][i]); } } - Zze
@Zze 是的,很相似! - Ele

0

迭代器方法(如mapforEachfilter......)处理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)中,它接受像01这样的实数。在这里,代码可以处理它。


这个答案对我来说有点不清楚。将它保存在item中?代码可以处理它吗? 这是什么意思? - ViktorMS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接