当前位置 博文首页 > “Allen Su”的博客:【Dart】Dart 之 singleWhere 查找数组中唯

    “Allen Su”的博客:【Dart】Dart 之 singleWhere 查找数组中唯

    作者:[db:作者] 时间:2021-07-07 22:02

    Dart 查找数组中唯一满足条件的元素,用 singleWhere ,源代码定义如下

    E lastWhere(bool test(E element), {E orElse()})
    

    返回值为泛型,参数 test 为指定的条件,返回值为 bool,第二个参数 orElse 为可选参数,是当数组中没有满足指定条件的元素设置的自定义值。

    List<int> l1 = [8, 12, 4, 1, 17, 33, 10];
    int a = l1.singleWhere((e) => e > 30);
    int b = l1.singleWhere((e) => e > 10);
    int c = l1.singleWhere((e) => e > 10, orElse: () => -1);
    int d = l1.singleWhere((e) => e > 40, orElse: () => -1);
    
    print(a); // 33
    print(b); // 报错
    print(c); // 报错
    print(d); // -1
    

    在使用 singleWhere 时,要注意 以下几点

    • 当数组中仅有一个满足条件的元素时,返回该元素
    • 当数组中有多个满足条件的元素时,报错
    • 当数组中有多个满足条件的元素时,即使设置了 orElse ,也会报错
    • 当数组中没有满足条件的元素时,返回 orElse 指定的返回值

    更多 Dart 中 List 数组的方法,推荐一篇博客 Dart 中 List 数组的常用方法


    结束语

    如果这篇博客有幸帮到了您,欢迎点击下方链接,和更多志同道合的伙伴一起交流,一起进步。

    开发者俱乐部
    在这里插入图片描述

    cs