类中BS()与compute()调用导致alert重复触发,如何修复?
修复两次触发alert及compute无效判断的问题
问题根源
compute()方法中连续调用了两次this.BS(),第一次用于判断,第二次用于计算,导致BS()里的alert被触发两次。- 当weight为空时,
BS()执行return alert(...),而alert()的返回值是undefined:用if(this.BS()== null)宽松相等判断时,undefined == null为true,但因两次调用BS(),alert仍会弹两次;若用严格相等===,undefined === null为false,判断直接失效。
修复方案
核心思路是只调用一次BS()并保存结果,避免重复触发alert;同时让BS()返回明确的标记值,确保compute()能准确判断是否执行后续逻辑。
优化后的代码示例
BS() { this.weight = document.getElementById('first').value; this.height = document.getElementById('second').value; // 检查weight是否为空 if (this.weight === '') { alert('please enter weight'); return null; // 返回明确的空标记 } const w = parseFloat(this.weight); const h = parseFloat(this.height); // 检查是否为有效数字 if (isNaN(w) || isNaN(h)) { alert('Please enter valid numbers'); return null; } return w * h; } compute() { // 只调用一次BS并保存结果 const bmValue = this.BS(); // 判断结果是否为null或NaN,满足则直接返回 if (bmValue === null || isNaN(bmValue)) { return; } return bmValue / 10; }
可选优化:单一职责拆分
如果想让BS()只负责计算逻辑,把弹窗提示移到compute()中(更符合单一职责原则),可以这样写:
BS() { this.weight = document.getElementById('first').value; this.height = document.getElementById('second').value; if (this.weight === '') { return null; } const w = parseFloat(this.weight); const h = parseFloat(this.height); if (isNaN(w) || isNaN(h)) { return null; } return w * h; } compute() { const bmValue = this.BS(); if (bmValue === null || isNaN(bmValue)) { // 只在判断不通过时触发一次弹窗 if (this.weight === '') { alert('please enter weight'); } else { alert('Please enter valid numbers'); } return; } return bmValue / 10; }
内容的提问来源于stack exchange,提问作者Mari
相关产品推荐
相关产品推荐

