亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將每個數組元素映射到不同的函數

將每個數組元素映射到不同的函數

慕田峪9158850 2022-10-27 14:37:07
有沒有辦法將數組中的每個元素直接映射到單獨的函數中,并將每個函數的結果返回到該元素的單獨變量中?例如,我有這個代碼:arry = ["22-03-1995", 80.5, 1.83];born   = process_date(arry[0]);     // call specific function for 1st elementweight = process_weight(arry[1]);   // call specific function for 2nd elementheight = process_height(array[2]);  // call specific function for 3rd element...function process_date(d) { ... }function process_weight(w) { ... }function process_height(h) { ... } 或這種替代方法以更好的更短形式實現相同的目的。
查看完整描述

3 回答

?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

如果您只想映射一個數組,那么您可能需要這樣的東西:


const [born, weight, height] = [

  process_date(arry[0]),

  process_weight(arry[1]),

  process_height(array[2])

]

如果有多個數組,則需要自己處理,您可以創建一個函數,該函數接受輸入數組并返回映射數組:


function mapArray(arr) {

  return [

    process_date(arr[0]),

    process_weight(arr[1]),

    process_height(arr[2])

  ]

}


arry.forEach(arr => {

  const [born, weight, height] = mapArray(arr);

  // do stuff with the variables here...

})


查看完整回答
反對 回復 2022-10-27
?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

您可以將函數放入對象中。然后將你的值放入一個對象數組中,這樣你就可以擁有元數據來告訴值它應該調用什么函數。


例子


const valueObjects = [{

    type: "date",

    value: "22-03-1995"

}, {

    type: "weight",

    value: 80.5

}]


const calculations = {

    date: function process_date(d) {...},

    weight: function process_weight(w) {...}

};


valueObjects.forEach(valueObject => {

    const processType = calculations[valueObject.type];

    processType(valueObject.value);


})


查看完整回答
反對 回復 2022-10-27
?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

希望這可以幫到你


arry = ["22-03-1995", 80.5, 1.83];

arrayFunc = [function process_date(d) { ... }, function process_weight(w) { ... },  function process_height(h) { ... } ]


array.forEach(myFunction);


let results = []

function myFunction(item, index) {

  results << arrayFunc[index](item)


let born, weight, height; 

[born, weight, height] = results;


console.log(born);

console.log(weight);

console.log(height);


查看完整回答
反對 回復 2022-10-27
  • 3 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號