如何基于升序一个参数调用方法?

问题描述 投票:0回答:1

我打电话的方法多次:

displayA(aTotal, sectorTotalValue, templateItems);
displayB(bTotal, sectorTotalValue, templateItems);
...many more times

我想在基于aTotalbTotal等升序来调用这些。

所以,如果bTotal > aTotal话,我希望他们在这个顺序被称为:

displayB(bTotal, sectorTotalValue, templateItems);
displayA(aTotal, sectorTotalValue, templateItems);

如果bTotal < aTotal然后我希望他们被称为顺序如下:

displayA(aTotal, sectorTotalValue, templateItems);
displayB(bTotal, sectorTotalValue, templateItems);

我怎样才能做到这一点?

javascript
1个回答
1
投票

下面是基于把变量到一个数组,自定义排序的方法:

const displayCalls = [
     { total: aTotal, func: displayA },
     { total: bTotal, func: displayB },
];

//sort array to put highest total first
displayCalls.sort((call1, call2) => call2.total - call1.total);

//call each one in order
displayCalls.forEach(call => {
    call.func(call.total, sectorTotalValue, templateItems);
});
© www.soinside.com 2019 - 2024. All rights reserved.