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

    “Allen Su”的博客:【Dart】Dart 之 lastWhere 倒序查找数组

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

    Dart 倒序查找数组中第一个满足条件的元素,用 lastWhere () 方法,源代码定义如下

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

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

    例 1

      List<int> l1 = [8, 12, 4, 1, 17, 33, 10];
      
      int a = l1.firstWhere((e) => e > 10);
      int b = l1.firstWhere((e) => e > 50, orElse: () => -1);
      int c = l1.firstWhere((e) => e > 50);
      
      print(a); // 33  当前数组倒序第一个比 10 大的元素是 33
      print(b); // -1 当前数组中没有比 50 更大的元素,所以返回 orElse 中我们预先设置好的值
      print(c); // 如果数组中没有符合条件的元素,而且也没有指定 orElse ,则会错误
    

    例 2

      List<String> l2 = ["一月", "二月", "三月", "四月"];
      String str = l2.lastWhere((e) => e.contains("月"));
      print(str); // 四月
    

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


    结束语

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

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

    cs