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

有没有办法将数组中的每个元素直接映射到单独的函数中,并将每个函数的结果返回到该元素的单独变量中?


例如,我有这个代码:


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


born   = process_date(arry[0]);     // call specific function for 1st element

weight = process_weight(arry[1]);   // call specific function for 2nd element

height = process_height(array[2]);  // call specific function for 3rd element


...


function process_date(d) { ... }

function process_weight(w) { ... }

function process_height(h) { ... } 

或这种替代方法以更好的更短形式实现相同的目的。


慕田峪9158850
浏览 78回答 3
3回答

慕姐8265434

如果您只想映射一个数组,那么您可能需要这样的东西: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...})

墨色风雨

您可以将函数放入对象中。然后将你的值放入一个对象数组中,这样你就可以拥有元数据来告诉值它应该调用什么函数。例子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);})

慕妹3242003

希望这可以帮到你arry = ["22-03-1995", 80.5, 1.83];arrayFunc = [function process_date(d) { ... }, function process_weight(w) { ... },&nbsp; function process_height(h) { ... } ]array.forEach(myFunction);let results = []function myFunction(item, index) {&nbsp; results << arrayFunc[index](item)}&nbsp;let born, weight, height;&nbsp;[born, weight, height] = results;console.log(born);console.log(weight);console.log(height);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript