Javascript映射在二维数组

时间:2018-03-05 22:54:33

标签: 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])
        );

这是如何运作的?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我会假设您根本不习惯这里使用的特定语言功能,因此您无法关注正在发生的事情,所以这里有:

  • 您的结构是嵌套的Array。因此嵌套的Array.map s。

  • 两个map回调都使用了implicit return

展现了这个:

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

传递给map回调的2个参数如下:

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

这就是它的全部。从那时起,您只需遵循每次迭代时迭代和每个参数的值。

答案 2 :(得分:0)

处理迭代器2d的迭代器方法(例如mapforEachfilter ...),因为每个元素都是1d数组

例如:

    arr= [[1,0,0],
          [0,1,0],
          [0,0,1]]
    arr.map( (item)=> {
           item.forEach( (element)=> {
             //...
            //...
           })
    })

在此示例中,第一个迭代器(map)在arr数组中占据第一行[1,0,0]

第二个迭代器采用[0,1,0]的第二行arr,将其保存在项目中,依此类推...

在一个嵌套循环(foreach)中,它采用实数,例如01。这里的代码可以处理它。

相关问题