使用数组
数组类型是相同类型值的有序序列。
数组语法
数组字面量包含用方括号 ([]
) 括起来的值(也称为元素)序列。值用逗号分隔,并且必须是相同的类型。
示例数组
["1st", "2nd", "3rd"]
[1.23, 4.56, 7.89]
[10, 25, -15]
引用数组中的值
使用方括号表示法来引用数组中的值。 Flux 数组使用从零开始的索引。提供要引用的值的索引。
arr = ["1st", "2nd", "3rd"]
arr[0]
// Returns 1st
arr[2]
// Returns 3rd
操作数组
迭代数组
- 导入
experimental/array
包。 - 使用
array.map
迭代数组中的元素,将函数应用于每个元素,然后返回一个新数组。
import "experimental/array"
a = [
{fname: "John", lname: "Doe", age: 42},
{fname: "Jane", lname: "Doe", age: 40},
{fname: "Jacob", lname: "Dozer", age: 21},
]
a |> array.map(fn: (x) => ({statement: "${x.fname} ${x.lname} is ${x.age} years old."}))
// Returns
// [
// {statement: "John Doe is 42 years old."},
// {statement: "Jane Doe is 40 years old."},
// {statement: "Jacob Dozer is 21 years old."}
// ]
检查数组中是否存在值
使用 contains
函数 检查数组中是否存在值。
names = ["John", "Jane", "Joe", "Sam"]
contains(value: "Joe", set: names)
// Returns true
获取数组的长度
使用 length
函数 获取数组的长度(数组中元素的数量)。
names = ["John", "Jane", "Joe", "Sam"]
length(arr: names)
// Returns 4
从数组创建表流
- 导入
array
包。 - 使用
array.from()
返回 表流。输入数组必须是 记录 数组。记录中的每个键值对表示一列及其值。
import "array"
arr = [
{fname: "John", lname: "Doe", age: "37"},
{fname: "Jane", lname: "Doe", age: "32"},
{fname: "Jack", lname: "Smith", age: "56"},
]
array.from(rows: arr)
输出
fname | lname | age |
---|---|---|
John | Doe | 37 |
Jane | Doe | 32 |
Jack | Smith | 56 |
比较数组
使用 ==
比较运算符 检查两个数组是否相等。 相等性基于值、其类型和顺序。
[1,2,3,4] == [1,3,2,4]
// Returns false
[12300.0, 34500.0] == [float(v: "1.23e+04"), float(v: "3.45e+04")]
// Returns true
过滤数组
- 导入
experimental/array
包。 - 使用
array.filter
迭代并使用谓词函数评估数组中的元素,然后返回一个仅包含与谓词匹配的元素的新数组。
import "experimental/array"
a = [1, 2, 3, 4, 5]
a |> array.filter(fn: (x) => x >= 3)
// Returns [3, 4, 5]
合并两个数组
- 导入
experimental/array
包。 - 使用
array.concat
合并两个数组。
import "experimental/array"
a = [1, 2, 3]
b = [4, 5, 6]
a |> array.concat(v: b)
// Returns [1, 2, 3, 4, 5, 6]
返回数组的字符串表示形式
使用 display()
返回数组的 Flux 字面量表示形式作为字符串。
arr = [1, 2, 3]
display(v: arr)
// Returns "[1, 2, 3]"
在表中包含数组的字符串表示形式
使用 display()
返回数组的 Flux 字面量表示形式作为字符串,并将其包含为列值。
import "sampledata"
sampledata.string()
|> map(fn: (r) => ({_time: r._time, exampleArray: display(v: [r.tag, r._value])}))
输出
_time (time) | exampleArray (string) |
---|---|
2021-01-01T00:00:00Z | [t1, smpl_g9qczs] |
2021-01-01T00:00:10Z | [t1, smpl_0mgv9n] |
2021-01-01T00:00:20Z | [t1, smpl_phw664] |
2021-01-01T00:00:30Z | [t1, smpl_guvzy4] |
2021-01-01T00:00:40Z | [t1, smpl_5v3cce] |
2021-01-01T00:00:50Z | [t1, smpl_s9fmgy] |
2021-01-01T00:00:00Z | [t2, smpl_b5eida] |
2021-01-01T00:00:10Z | [t2, smpl_eu4oxp] |
2021-01-01T00:00:20Z | [t2, smpl_5g7tz4] |
2021-01-01T00:00:30Z | [t2, smpl_sox1ut] |
2021-01-01T00:00:40Z | [t2, smpl_wfm757] |
2021-01-01T00:00:50Z | [t2, smpl_dtn2bv] |
此页内容对您有帮助吗?
感谢您的反馈!