如何以有效的方式获取 Ballerina 数组中对象的索引?
是否有任何内置功能可以做到这一点?
最佳答案
Ballerina 现在提供 indexOf
和 lastIndexOf
方法,自语言规范 2020R1 起。
它们分别返回满足等式的项目的第一个和最后一个索引。我们得到 ()
如果未找到该值。
import ballerina/io;
public function main() {
string[*] example = ["this", "is", "an", "example", "for", "example"];
// indexOf returns the index of the first element found
io:println(example.indexOf("example")); // 3
// The second parameter can be used to change the starting point
// Here, "is" appears at index 1, so the return value is ()
io:println(example.indexOf("is", 3) == ()); // true
// lastIndexOf will find the last element instead
// (the implementation will do the lookup backwards)
io:println(example.lastIndexOf("example")); // 5
// Here the second parameter is where to stop looking
// (or where to start searching backwards from)
io:println(example.lastIndexOf("example", 4)); // 3
}
Run it in the Ballerina Playground
这些和其他功能的描述可以在 in the spec 中找到。 .
关于arrays - 如何在 Ballerina Array 中获取对象的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201810/