如何从Kotlin数组中获取值的索引?
我现在最好的解决方案是使用:
val max = nums.max()
val maxIdx = nums.indices.find({ (i) -> nums[i] == max }) ?: -1
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
小智 16
如果要获取最大元素的索引,可以使用'maxBy'函数:
val maxIdx = nums.indices.maxBy { nums[it] } ?: -1
Run Code Online (Sandbox Code Playgroud)
它更有效,因为它只遍历数组一次.
使用当前的Kotlin(1.0),您可以在数组上使用indexOf()
扩展功能:
val x = arrayOf("happy","dancer","jumper").indexOf("dancer")
Run Code Online (Sandbox Code Playgroud)
在你的例子中:
val maxIdx = nums.indexOf(nums.max())
Run Code Online (Sandbox Code Playgroud)