I noticed that forEach
and for in
to produce different behavior. I have a list of RegExp
and want to run hasMatch
on each one. When iterating through the list using forEach
, hasMatch
never returns true. However, if I use for in
, hasMatch
returns true.
Sample code:
class Foo {
final str = "Hello";
final regexes = [new RegExp(r"(w+)")];
String a() {
regexes.forEach((RegExp reg) {
if (reg.hasMatch(str)) {
return 'match';
}
});
return 'no match';
}
String b() {
for (RegExp reg in regexes) {
if (reg.hasMatch(str)) {
return 'match';
}
}
return 'no match';
}
}
void main() {
Foo foo = new Foo();
print(foo.a()); // prints "no match"
print(foo.b()); // prints "match"
}
(DartPad with the above sample code)
The only difference between the methods a
and b
is that a
uses forEach
and b
uses for in
, yet they produce different results. Why is this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…