代码之家  ›  专栏  ›  技术社区  ›  Quentin

根据列表的长度循环多个列表

  •  -1
  • Quentin  · 技术社区  · 5 年前

    var list_1 = [...]    // length 24
    var list_2 = [...]    // length 4
    var list_3 = [...]    // length 3
    var list_4 = [...]    // length 4
    var list_5 = [...]    // length 11
    var list_6 = [...]    // length 2
    
    // Need code here for loop each list in order asc
    list_6.forEach(...)   // length 2
    list_3.forEach(...)   // length 3
    list_2.forEach(...)   // length 4
    list_4.forEach(...)   // length 4
    list_5.forEach(...)   // length 11
    list_1.forEach(...)   // length 24
    

    有人有简单的解决方案吗?谢谢

    1 回复  |  直到 5 年前
        1
  •  6
  •   Nina Scholz    5 年前

    您可以将列表添加到数组中,对其进行排序并执行循环

    [list, list2, ...]
        .sort((a, b) => a.length - b.length)
        .forEach(array => array.forEach(...))
    
        2
  •  1
  •   Marek W    5 年前

    const list1 = [1, 2, 3, 4],
      list2 = [1],
      list3 = [1, 2, 3, 4, 5, 6, 7];
    
    let listOfLists = [list1, list2, list3].sort((a, b) => a.length - b.length);
    
    console.log(listOfLists);
    listOfLists.forEach(list => {
      list.forEach(itemInList => {
        console.log(itemInList);
      });
    });

    看见 StackBlitz 实例

    推荐文章