在 JavaScript 中,Array.map() 函式的存在使得
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
我需要一個 bash 等效項,我可以在其中獲取我的陣列,操作其內容,然后接收一個帶有操作的新陣列。
array1=(1 4 9 16)
map1=# ????
echo ${map1[*]}
uj5u.com熱心網友回復:
Soooooooo,只需撰寫回圈。
array1=(1 4 9 16)
map1=()
for i in "${array1[@]}"; do
map1 =("$((i * 2))")
done
echo "${map1[@]}"
可能是重新閱讀 Bash 陣列介紹的好時機。
uj5u.com熱心網友回復:
可以通過回呼實作一個array_walk對每個元素執行操作的方法:
#!/usr/bin/env bash
# Applies the user-defined callback function to each element of the array.
#
# @params
# $1: The array name to walk
# $2: The callback command or function name
array_walk() {
local -n __array=$1
local -- __callback=$2 __i
for __i in "${!__array[@]}"; do
"$__callback" "$1[$__i]"
done
}
x2() {
local -n __e=$1
__e=$((2 * __e))
}
array1=(1 4 9 16)
array_walk array1 x2
printf '%s\n' "${array1[*]}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420213.html
標籤:
上一篇:從大字串中提取多次出現的可變資料
