如何访问 bash 关联数组的最后一个元素?

问题描述 投票:0回答:1

我正在尝试使用以下代码访问 bash 关联数组的最后一个元素: # 声明一个关联数组 声明 -A myAssocArray

# Add key-value pairs to the associative array
myAssocArray["name"]="John"
myAssocArray["age"]=30
myAssocArray["city"]="New York"
myAssocArray["country"]="USA"

keys=("${!myAssocArray[@]}")  # Get all keys
last_key="${keys[-1]}"        # Access the last key
last_element="${myAssocArray[$last_key]}"  # Access the last elemen
echo "$last_element"

它输出:约翰而不是美国 实际上我正在尝试寻找是否有任何方法可用,例如对 assoc 中最后一个元素访问的负索引。数组

linux bash shell element associative-array
1个回答
0
投票

问题是 Bash 中的关联数组是无序的,因此不能保证循环中访问的最后一个元素将是添加到数组中的实际最后一个元素,但如果您想在不使用关联的情况下访问数组的最后一个元素数组,您可以使用常规索引数组并使用负索引访问最后一个元素。

myArray=("John" 30 "New York" "USA")

#get the length of the array
length=${#myArray[@]}

#access the last element using negative index
last_element="${myArray[length-1]}"

echo "$last_element"

输出

USA
© www.soinside.com 2019 - 2024. All rights reserved.