for (item in collection.size - 1 downTo 0) { //迭代操作 } ``` 上述代码将会从集合的最后一个元素开始迭代到第一个元素。 5.带有索引的for循环 如果我们既需要访问元素,又需要访问索引,可以使用withIndex()方法。它会返回一个带有索引的迭代器。例如: ```kotlin for ((index, item) in collection.wi...
而如果下标和元素都需要呢?答案是withIndex函数 for((index,value)inabc.withIndex()){print("$index:$value ")}>>>0:a1:b2:c 2人点赞 日记本 更多精彩内容,就在简书APP "如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!" ...
for ((index, value) in intArray.withIndex()) { Log.e(TAG, "for语句:withIndex == index: $index, value: $value") } 1. 2. 3. 4. 5. 打印数据如下: for语句:withIndex == index: 0, value: 10 for语句:withIndex == index: 1, value: 20 for语句:withIndex == index: 2, value:...
5. 使用forEach和lambda表达式 对于集合,可以使用forEach方法和lambda表达式来简化代码。 代码语言:txt 复制 val numbers = listOf(1, 2, 3, 4, 5) numbers.forEach { number -> println(number * 2) } 6. 使用withIndex 如果你需要同时访问元素的索引和值,可以使用withIndex。 代码语言:txt 复制 val fr...
使用数组的withIndex()方法遍历: val str = arrayOf("kotlin", "is", "best", "language") for ((i, value) in str.withIndex()) { println("$i $value") } 结果: 0 kotlin 1 is 2 best 3 language while、do...while循环: while和do...while是最基本的循环,与Java基本一致。 while( 布...
for (index in array.indices) { } 反编译后: for(int var4 = array.length; var3 < var4; ++var3) { } 通过indices 遍历数组, 编译之后的代码 ,除了创建了一些临时变量,并没有创建额外的对象。 通过withIndex 遍历数组 withIndex 和indices 遍历数组的方式相似,通过 withIndex 遍历数组,不仅可以获取的...
let,with,run,apply,also函数区别 https://blog.csdn.net/u013064109/article/details/78786646 //kotlin 的集中for,不包含迭代器的方式val al =listOf("ab","ab","ab","ab","ab","ab")//对象方式for( value in al){ }//下标for( index in 5..6){ ...
for((index, element) in list.withIndex()) { println("this $index is $element") } } * 中缀调用可以与之哟普一个参数的参数的函数一起使用,无论是普通的函数还是扩展函数。 * 要允许使用中缀符号调用函数,需要使用infix修饰符来标记它。 * 下面是一个简单的to函数的声明 ...
1、通过forEach遍历数组。 2、通过区间表达式遍历数组(.. 、 downTo 、 until)。 3、通过indices遍历数组。 4、通过withIndex遍历数组。 通过forEach 遍历数组 先来看看通过forEach遍历数组,和其他的遍历数组的方式,有什么不同。 array.forEach { value -> ...
withIndex函数,它返回一个Iterable对象,该对象可以被解构为当前索引和元素。 for ((index, arg) in args.withIndex()) { println("$index: $arg") } forEachIndexed函数,它为每个索引和参数提供了一个 lambda 表达式。 args.forEachIndexed { index, arg -> ...