当前位置 博文首页 > “Allen Su”的博客:【Dart】Dart 之 indexWhere、lastIndexWhe

    “Allen Su”的博客:【Dart】Dart 之 indexWhere、lastIndexWhe

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

    Dart 返回数组中第一个满足条件的元素的索引,用 indexWhere() 方法或者 lastIndexWhere() 方法 ,其中 indexWhere 方法是从前往后找,lastIndexWhere方法是从后往前找,下面分别举例说明。

    indexWhere 方法的源代码定义如下

    int indexWhere(bool test(E element), [int start = 0]);
    

    返回值为 int ,第一个参数为要查找的条件,返回 bool,如果存在满足条件的元素返回 true,反之返回 false 。第二个参数为从哪个索引开始查找,是可选参数,默认为 0。

    例 1

      List<String> l1 = ["一月", "二月", "三月", "四月", "三月"];
    
      int a = l1.indexWhere((e) => e == "三月");
      int b = l1.indexWhere((e) => e == "三月", 3);
      int c = l1.indexWhere((e) => e == "十二月");
    
      print(a); // 2 从数组起始位置开始查找第一次出现"三月"的元素,返回该元素所在的索引
      print(b); // 4 从数组索引为 3 开始向后查找第一次出现"三月"的元素,返回该元素所在的索引
      print(c); // -1 数组中不存在"十二月",返回 -1 
    

    lastIndexWhere 方法源代码定义如下

    int lastIndexWhere(bool test(E element), [int start]);
    

    和 indexWhere 方法一样,只不过是从后向前倒序查找,相似之处不再赘述。

    例 2

      List<int> l1 = [8, 12, 4, 1, 17, 33, 10];
      
      int a = l1.lastIndexWhere((e) => e > 10);
      int b = l1.lastIndexWhere((e) => e > 10, 2);
      int c = l1.lastIndexWhere((e) => e > 10, 4);
      int d = l1.lastIndexWhere((e) => e > 50);
      
      print(a); // 5 当前数组倒序第一个比 10 大的元素是 33,该元素的索引是 5
      print(b); // 1
      print(c); // 4
      print(d); // 当前数组中没有比 50 大的数,返回 -1
    

    特别说明:lastIndexWhere 方法只是从后向前查,返回的还是指定元素所在的索引,不要误以为索引也是从后先前由0开始了

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


    结束语

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

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

    cs