如何以有效的方式获取 Ballerina 数组中对象的索引?是否有任何内置功能可以做到这一点?
问问题
274 次
1 回答
1
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
}
这些和其他功能的描述可以在规范中找到。
于 2020-04-17T04:25:09.403 回答