gpt4 book ai didi

groovy - 是否有任何隐式变量可以访问 "each"方法中的项目索引

转载 作者:行者123 更新时间:2023-12-01 22:58:23 25 4
gpt4 key购买 nike

是否有任何方法可以删除以下示例中的变量“i”,并且仍然可以访问正在打印的项目的索引?

def i = 0;
"one two three".split().each {
println ("item [ ${i++} ] = ${it}");
}

================编辑================

我发现一种可能的解决方案是使用“eachWithIndex”方法:

"one two three".split().eachWithIndex  {it, i
println ("item [ ${i} ] = ${it}");
}

如果还有其他解决方案,请告诉我。

最佳答案

您可以使用eachWithIndex()

"one two three four".split().eachWithIndex() { entry, index ->
println "${index} : ${entry}" }

这将导致

0 : one
1 : two
2 : three
3 : four

关于groovy - 是否有任何隐式变量可以访问 "each"方法中的项目索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10380074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com