为了账号安全,请及时绑定邮箱和手机立即绑定

将每个数组元素映射到不同的函数

将每个数组元素映射到不同的函数

慕田峪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 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信