如何在 Ballerina Array 中获取对象的索引?

Riv*_*han 5 arrays ballerina

如何以有效的方式获取 Ballerina 数组中对象的索引?是否有任何内置功能可以做到这一点?

Kev*_*sco 1

Ballerina 现在提供自语言规范 2020R1 起的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
}
Run Code Online (Sandbox Code Playgroud)

在芭蕾舞游乐场运行它

这些功能和其他功能的描述可以在规范中找到。