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

标签 arrays 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 中找到。 .

关于arrays - 如何在 Ballerina Array 中获取对象的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201810/

相关文章:

arrays - 给定一个数字和字符数组,找到两者数量相等的最长连续子数组

java - Java 中的单独链接

C语言: Copying strings one by one to an array

sql - 使用 postgresql 创建记录时出现编译时错误 :jsonvalue type in Ballerina

ballerina - 在 Ballerina 中运行测试用例时遇到错误 : Failed to Start Debug Adapter

json - 优化流到 JSON 的转换以提高性能和内存效率

c - 我在代码中遇到问题,应该找到字符串中子字符串的出现次数

PHP 将数组格式如 first_name 更改为 First Name