我有一个数组[2,5,1]
$,它是价格,客户为第一个项目支付2
$,因为第一个项目没有折扣,
5-2 = 3
对于第二项,
min(第一项,第二项) min(2,5) = 2
对于第三项;但如果下一个项目的成本低于第二个项目,例如1 小于 2 成本为零;
so 2+3+0 is output of calculate price.
如果我还有一个输入
[2,5,1,6]
2 + (5-2) + 0 + (6 - min(2,5,1))
我如何才能实现这一目标 -
我试图写这样的东西 -
function calculateAmount(prices) {
// Write your code here
var totalCostPurchase;
var cost = [];
var zero = 0;
for (var i = 0; i < prices.length; i++) {
if (i === 0) {
cost.push(prices[i]);
} else if (i === 1) {
cost.push(prices[i] - cost[i - 1]);
} else {
var minCost = Math.min(...prices.slice(0,i));
console.log(minCost);
if (minCost > prices[i]) {
cost.push(zero);
} else {
cost.push(prices[i] - minCost);
}
}
}
totalCostPurchase = cost.reduce((a, b) => a + b, 0);
console.log(totalCostPurchase);
return totalCostPurchase;
}
Please guide.
最佳答案
您可以为此使用Array.map
和Array.reduce
var a = [2,5,1,6]
let res = a.map((d,i) => i != 0
? d - Math.min(...a.slice(0, i+1))
: d)
.reduce((x, y) => x + y)
console.log(res)
关于创建 JavaScript 函数以根据某些信息计算价格(示例 - 商店报价),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465237/