[英]Groovy each() method does not iterate properly
I came across a strange behavior of the each() method when trying this code: 尝试以下代码时,我遇到了each()方法的奇怪行为:
def xml = new XmlSlurper().parseText('''
<list>
<item a="1">a</item>
<item a="2">b</item>
<item a="1">c</item>
</list>
''')
def i = 0
xml.'**'.findAll { it.@a=='1' }.each {
println "hi" + i
}
The result is only hi0
, however I would expect hi0hi1
. 结果只是
hi0
,但是我希望hi0hi1
。 Is this behavior a bug or per language design? 这是错误还是每种语言设计? The second result is only provided if I write
println "hi" + i++
instead of the current closure body, so when the content is different for each item... 仅当我写
println "hi" + i++
而不是当前的闭包主体时,才提供第二个结果,所以当每个项目的内容都不同时...
Your i
variable is not being incremented because there's nothing that tells it to increment. 您的
i
变量未递增,因为没有任何内容告诉它递增。 The way your code is currently written, I would expect the output to be: 当前编写代码的方式,我希望输出为:
hi0
hi0
I think what you are looking for is eachWithIndex
, which provides the closure with two arguments - the current item and the index of the item. 我认为您正在寻找的是
eachWithIndex
,它为闭包提供了两个参数-当前项目和该项目的索引。 Your code would then look like this: 您的代码将如下所示:
def xml = new XmlSlurper().parseText('''
<list>
<item a="1">a</item>
<item a="2">b</item>
<item a="1">c</item>
</list>
''')
xml.'**'.findAll { it.@a=='1' }.eachWithIndex { item, i ->
println "hi" + i
}
This results in an output of: 结果是:
hi0
hi1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.