求实现按优先级从FieldC、FieldB、FieldA依次扣减数值的JavaScript方案
实现分步扣除逻辑的JavaScript方案
Got it, let's work through this step-by-step deduction logic you need. Here's a clean, straightforward JavaScript function that follows your exact requirements—no direct subtraction from the total SUM, just adjusting each field in the specified priority order (C → B → A):
function deductFromFields(fieldA, fieldB, fieldC, deductionAmount = 75) { let remainingDeduction = deductionAmount; // 先从FieldC扣除 const deductedFromC = Math.min(remainingDeduction, fieldC); const newFieldC = fieldC - deductedFromC; remainingDeduction -= deductedFromC; // 如果还有剩余,从FieldB扣除 if (remainingDeduction > 0) { const deductedFromB = Math.min(remainingDeduction, fieldB); const newFieldB = fieldB - deductedFromB; remainingDeduction -= deductedFromB; // 如果还有剩余,从FieldA扣除 if (remainingDeduction > 0) { const deductedFromA = Math.min(remainingDeduction, fieldA); const newFieldA = fieldA - deductedFromA; return { fieldA: newFieldA, fieldB: newFieldB, fieldC: newFieldC }; } return { fieldA, fieldB: newFieldB, fieldC: newFieldC }; } return { fieldA, fieldB, fieldC: newFieldC }; }
怎么用这个函数?
Just pass in your field values, and it'll return the updated values after deduction. Let's test your example:
// 示例输入:FieldA=20、FieldB=30、FieldC=40 const result = deductFromFields(20, 30, 40); console.log(result); // 输出:{ fieldA: 15, fieldB: 0, fieldC: 0 } 完全符合你的要求!
逻辑说明
- 我们先处理FieldC:扣除的金额不会超过FieldC当前的值,扣完后更新剩余需要扣除的金额
- 如果剩余扣除额还大于0,再处理FieldB,同样只扣当前字段能承担的部分
- 最后如果还有剩余,从FieldA扣除剩余的部分
- 这个函数是纯函数,不会修改你传入的原始值,只会返回新的结果对象,避免意外修改数据
如果你的业务需要直接修改现有变量(而不是返回新对象),也可以调整函数逻辑,直接更新对应的变量即可。
内容的提问来源于stack exchange,提问作者Sherga
相关产品推荐
相关产品推荐

