【发布时间】:2018-07-06 01:11:21
【问题描述】:
如何以有效的方式获取 Ballerina 数组中对象的索引? 有没有内置函数可以做到这一点?
【问题讨论】:
-
我认为您需要为您的用例提出合适的搜索算法。我们目前没有任何内置方法。
如何以有效的方式获取 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找到。
【讨论】: