问题
I have created a 2D array named squareData as shown below:
private lateinit var squareData: Array<Array<String>>
squareData = Array(3, {Array(3, {""})})
Also, I initialized this array with some random values. Now I want to fetch this values one by one. How can I do it using for or forEachIndexed loop?
回答1:
You can iterate in the array like this :
for (strings in squareData) {
for (string in strings) {
Your code here
}
}
The first for iterate through the first dimension so it has string arrays and the second one through the second dimension so it has the string values
回答2:
You can use regular nested for loop.
for (arr in squareData) {
for (s in arr) {
println(s)
}
}
You can iterate using forEach
:
squareData.forEach { it.forEach(::println) }
or if you want index position as well, forEachIndexed
:
squareData.forEachIndexed { i,it -> println(i); it.forEach(::println) }
来源:https://stackoverflow.com/questions/47265260/parse-2d-array-in-kotlin