关联数组的声明和使用
Reverse Lv4

在 Vue 中

1
2
3
4
5
6
7
8
const IterateState = (row) => {
const state = {
1: "Success",
2: "Warning",
3: "Error",
};
return state[row] || "Unknown"; // 如果 row 不在对象中,返回 "Unknown"
};

在 Shell 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 声明一个关联数组
declare -A _cfg

# 给数组赋值
_cfg["sleep"]="this is sleep"
_cfg["data"]="this is data"
_cfg["name"]="this is name"
_cfg["type"]="this is type"

# 输出数组的值
echo "${_cfg["sleep"]}"
echo "${_cfg["data"]}"
echo "${_cfg["name"]}"
echo "${_cfg["type"]}"

# 输出所有键
echo "${!_cfg[@]}"

# 输出所有值
echo "${_cfg[@]}"

在 Go 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import "fmt"

func main() {
var cfg = map[string]string{
"sleep": "this is sleep",
"data": "this is data",
"name": "this is name",
"type": "this is type",
}

// 输出数组的值
fmt.Println(cfg["sleep"])
fmt.Println(cfg["data"])
fmt.Println(cfg["name"])
fmt.Println(cfg["type"])
}