当前位置 博文首页 > “Allen Su”的博客:【Dart】Dart 之 retainWhere 保留满足条件

    “Allen Su”的博客:【Dart】Dart 之 retainWhere 保留满足条件

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

    Dart 保留满足条件的元素,用 retainWhere 方法,该方法源代码定义如下

    void retainWhere(bool test(E element));
    

    该方法无返回值,参数 test 为指定的条件,返回 bool

      List<int> l1 = [8, 12, 4, 1, 17, 33, 10];
      l1.retainWhere((e) => e > 10);
      print(l1); // [12, 17, 33]
      
      List<int> l2 = [8, 12, 4, 1, 17, 33, 10];
      l2.retainWhere((e) => e > 40);
      print(l2); // [ ]
    

    在使用 retainWhere 时

    • 保留数组中满足条件的元素,移除不满足条件的元素,原数组发生改变
    • 如果数组中没有满足条件的元素,移除所有元素,返回长度为 0 的数组

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


    结束语

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

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

    cs