【问题标题】:Iterating through a matrix of irregular row lengths遍历不规则行长的矩阵
【发布时间】:2019-11-24 01:07:12
【问题描述】:

我有一个矩阵,其中行不一定具有相同的长度:

以下是唱名格式的音乐标记。

const notes = [
    [ 'do5', 'mi5' ],
    [ 'mi6', 'so6', 'ti6', 're7' ],
    [ 'so7', 'ti7', 're8', 'fa8' ],
    [ 'la3', 'do4', 'mi4' ],
    [ 'fa2', 'la2' ],
    [ 're2' ],
    [ 'ti1', 're2', 'fa2' ]
];

我有一个函数可以将这些标记转换为等效的字母标记(例如:fa2 将使用我的函数转换为 F2)。

我希望能够迭代这个矩阵,并返回转换后的矩阵,它应该保持相同的维度。

谢谢, 纳库尔

【问题讨论】:

  • 如果你有一个二维数组,你可以使用 2 map()s。
  • Array.forEach() 2 次​​span>
  • 您是否有任何已经尝试过的 JavaScript?我们不知道您可能知道或不知道什么。
  • 您刚刚更改了您需要返回“相同大小的矩阵”的问题。你到底是什么意思?
  • 我很抱歉@LucioPaiva,我刚刚修改了我的问题以更好地解释我的意思。

标签: javascript matrix iteration


【解决方案1】:

这就是你可能想要的:

const notes = [
    [ 'do5', 'mi5' ],
    [ 'mi6', 'so6', 'ti6', 're7' ],
    [ 'so7', 'ti7', 're8', 'fa8' ],
    [ 'la3', 'do4', 'mi4' ],
    [ 'fa2', 'la2' ],
    [ 're2' ],
    [ 'ti1', 're2', 'fa2' ]
];

// replace this function with your own converter
function convert(note) {
    return note.toUpperCase();
}

for (let i = 0; i < notes.length; i++) {  // for each row
    // map will iterate through the row, converting each note
    notes[i] = notes[i].map(convert);
}

map(convert) 部分只是map(note =&gt; convert(note)) 的缩写形式。

这不是很有效,因为map() 将为每一行创建一个新数组,但在您的情况下,代码的可读性可能比性能更重要,所以这很好。

【讨论】:

    【解决方案2】:

    你可以使用新的 Array.prototype.flat() 函数,但是,如果你想要更广泛的支持(.flat() 被 Edge 和 IE 忽略),那么我会使用两个 for..of 循环。

    const arr = [
      [ 'do5', 'mi5' ],
      [ 'mi6', 'so6', 'ti6', 're7' ],
      [ 'so7', 'ti7', 're8', 'fa8' ],
      [ 'la3', 'do4', 'mi4' ],
      [ 'fa2', 'la2' ],
      [ 're2' ],
      [ 'ti1', 're2', 'fa2' ]
    ];
    
    // Modern JavaScript
    for (const item of arr.flat()) {
      console.log(item);
    }
    
    console.log('----');
    
    // More widely supported JavaScript
    for (const subarray of arr) {
      for (const subitem of subarray) {
          console.log(subitem);
      }
    }

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 2022-01-22
      • 2016-02-12
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多