Google Dart:.where()函数如何工作? [英] Google Dart : How does .where() function work?
问题描述
var fruits = ['apples', 'oranges', 'bananas'];
fruits[0]; // apples
fruits.add('pears');
fruits.length == 4;
fruits.where((f) => f.startsWith('a')).toList();
文档中的示例显示了上述内容.我也不太了解该方法的文档.
The example in the documentation shows the above. I dont really understand the documentation of the method either.
https://api.dartlang.org/stable/1.21.1/dart-collection/IterableMixin/where.html
我目前看到lambda函数是where内的参数,其中where带有参数f.什么是f?我有点困惑.
I currently see a lambda function as a parameter inside where, with where having the argument f. What is f though? Im a bit confused.
如果我能看到一个可行的例子,那就太好了.就目前而言,我还没有真正理解它.除了它充当某种过滤器之外,我不知道它是如何工作的或者它实际上是做什么的.
It would be great if I could see a working example. As it stands now I dont really get it. I dont know how it works or what it really does apart from that it acts as some sort of filter.
推荐答案
是一个匿名函数, f
是它接受的参数
Is an anonymous function and f
is the parameter it accepts
(f) => f.startsWith('a')
where(...)
调用为 fruits
中的每个元素传递的函数,并返回一个仅返回函数返回 true <的值的可迭代对象/code>
where(...)
calls that passed function for each element in fruits
and returns an iterable that only emits the values where the function returned true
where(...)
是惰性的,因此,仅当实际访问结果时才进行传递函数的迭代和调用,例如使用 .toList()
.
where(...)
is lazy, therefore the iteration and call of the passed function will only happen when the result is actually accessed, like with .toList()
.
更新
匿名"是指该函数没有名称,与诸如的命名函数相反
"anonymous" means the function has no name in contrary to a named function like
myFilter(f) => f.startsWith('a');
main() {
fruits.where(myFilter).toList();
}
也
myFilter(f) => f.startsWith('a');
只是
myFilter(f) {
return f.startsWith('a');
}
这篇关于Google Dart:.where()函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!