数组的使用
一个 数组 类型是相同类型值的有序序列。
数组语法
数组字面量包含一系列值(也称为元素),用方括号包围([])。
值用逗号分隔,必须是相同类型。
示例数组
["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)
输出
| 名字 | 姓氏 | 年龄 |
|---|---|---|
| 约翰 | 杜 | 37 |
| 简 | 杜 | 32 |
| 杰克 | 史密斯 | 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 (时间) | exampleArray (字符串) |
|---|---|
| 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] |