首页 > 解决方案 > Bash 地图没有给出正确的结果

问题描述

我在 bash 中使用 map 如下:

declare -a hash
hash=(["a"]="A" ["b"]="B" ["c"]="C" ["d"]="D")

echo ${hash["a"]}

https://ideone.com/YfnazQ

但是它正在打印D而不是A. 这个片段有什么问题?

标签: bashdictionary

解决方案


您的问题就是您如何定义变量哈希。

declare -a hash用于索引数组,我的意思是索引只是数字的数组。

要声明关联数组,只需将 -a 更改为 -A:

declare -A hash

这样你就可以写字母作为索引,并且回显将按预期工作。

希望我有所帮助!


推荐阅读