遍历数组,既印刷指数和价值 [英] Looping over arrays, printing both index and value
本文介绍了遍历数组,既印刷指数和价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要做这样的事情:
foo=( )
foo[0]="bar"
foo[35]="baz"
for((i=0;i<${#foo[@]};i++))
do
echo "$i: ${foo[$i]}"
done
# Output:
# 0: bar
# 1:
然后我试图遍历它使用:
Then i tried to loop through it using for in:
foo=( )
foo[0]="bar"
foo[35]="baz"
for i in ${foo[@]}
do
echo "?: $i"
done
# Output:
# ?: bar
# ?: naz
但在这里,我不知道该指数值。
but here I don't know the index value.
我知道你可以像
foo=( )
foo[0]="bar"
foo[35]="baz"
declare -p foo
# Output:
# declare -a foo='([0]="bar" [35]="baz")'
但是,你不能做它以另一种方式?
but, can't you do it in another way?
推荐答案
您会找到$ {!foo的[@]}
(<一个数组键href=\"http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion\">reference),所以:
for i in "${!foo[@]}"; do
printf "%s\t%s\n" "$i" "${foo[$i]}"
done
这篇关于遍历数组,既印刷指数和价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文