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
);
List
<int> l2
= [8, 12, 4, 1, 17, 33, 10];
l2
.retainWhere((e
) => e
> 40);
print(l2
);
在使用 retainWhere 时
保留数组中满足条件的元素,移除不满足条件的元素,原数组发生改变如果数组中没有满足条件的元素,移除所有元素,返回长度为 0 的数组
更多 Dart 中 List 数组的方法,推荐一篇博客 Dart 中 List 数组的常用方法
结束语
如果这篇博客有幸帮到了您,欢迎点击下方链接,和更多志同道合的伙伴一起交流,一起进步。