如何在calculatePercents方法中将NULL%替换为0%
问题原因
你代码输出NULL的核心原因有两类:
- 当
this.v.global.cash.amount和this.v.global.sec.amount的和为0时,计算百分比的除数为0,会得到非数值结果 cash.amount或sec.amount本身为null/undefined,参与运算时会转为NaN,最终输出为NULL
解决方案
你可以先给两个金额设置默认值0,再提前判断总金额是否为0,避免除0报错,修改后的代码如下:
calculatePercents() { // 给金额字段兜底默认0,解决本身为null的问题 const cashAmount = this.v.global.cash.amount ?? 0 const secAmount = this.v.global.sec.amount ?? 0 const totalAmount = cashAmount + secAmount this.v.global.total.amount = totalAmount console.log("Cash => " + JSON.stringify(this.v.global.total.amount)); console.log('------------------------'); // 总金额为0时直接赋值0%,避免除0错误 if (totalAmount === 0) { this.v.global.cash.percent = 0 this.v.global.sec.percent = 0 } else { this.v.global.cash.percent = (cashAmount / totalAmount) * 100; this.v.global.sec.percent = (secAmount / totalAmount) * 100; } console.log(" Global cash " + JSON.stringify(this.v.global.cash.percent)); console.log(" NULL ???? ==> " + JSON.stringify(this.v.global.sec.percent)); const totPercent = this.v.global.cash.percent + this.v.global.sec.percent; this.v.global.total.percent = totPercent; }
如果你的运行环境不支持ES2020的空值合并运算符??,可以替换为更兼容的写法:
const cashAmount = this.v.global.cash.amount || 0 const secAmount = this.v.global.sec.amount || 0
内容的提问来源于stack exchange,提问作者user16922609
相关产品推荐
相关产品推荐

