有没有办法在以下示例中删除变量"i",仍然可以访问正在打印的项目的索引?
def i = 0;
"one two three".split().each {
println ("item [ ${i++} ] = ${it}");
}
Run Code Online (Sandbox Code Playgroud)
===============编辑================
我发现一种可能的解决方案是使用"eachWithIndex"方法:
"one two three".split().eachWithIndex {it, i
println ("item [ ${i} ] = ${it}");
}
Run Code Online (Sandbox Code Playgroud)
如果有其他解决方案,请告诉我.
小智 12
您可以使用 eachWithIndex()
"one two three four".split().eachWithIndex() { entry, index ->
println "${index} : ${entry}" }
Run Code Online (Sandbox Code Playgroud)
这将导致
0 : one
1 : two
2 : three
3 : four
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1150 次 |
| 最近记录: |