如何以有效的方式获取Ballerina数组中对象的索引?有没有内置的函数可以做到这一点?
发布于 2020-04-17 12:25:09
从语言规范2020R1开始,Ballerina现在提供了indexOf和lastIndexOf方法。
它们分别返回满足相等的项的第一个和最后一个索引。如果没有找到值,我们会得到()。
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
}这些函数和其他函数的描述可以在in the spec中找到。
https://stackoverflow.com/questions/51201810
复制相似问题