【问题标题】:How to `map` an `Iterable` partially in Dart?如何在 Dart 中部分地“映射”一个“Iterable”?
【发布时间】:2023-01-04 20:38:46
【问题描述】:

假设我有一个 List,如下所示:

final numbers = [1, 0, -1, 1, -3, 0];

我想生成另一个列表,其中 1 结果为 true 和 0 结果为 false 并跳过其他列表。所以,换句话说,我想要一个像 map 这样的方法,我也可以在其中跳过一些元素。在测试方面,它将断言:

expect(newList, equals([true, false, true, false]));

在这个结果中,我想跳过列表中的-1 和-3。

我怎样才能做到这一点?


环境

  • 飞镖 2.18.5

【问题讨论】:

    标签: dart


    【解决方案1】:

    使用 .where() 方法:

    final numbers = [1, 0, -1, 1, -3, 0];
    final result = numbers.where((n) => n == 1 || n == 0).map((n) => n == 1);
    print(result);
    
    \ (true, false, true, false)
    

    【讨论】:

      猜你喜欢
      • 2020-10-24
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 2016-12-27
      • 2023-03-15
      • 1970-01-01
      • 2019-10-13
      • 2021-12-10
      相关资源
      最近更新 更多