React应用中/运算符被识别为+的异常问题排查
问题根源:赋值运算符代替了比较运算符
你遇到的这个问题属于JS里非常典型的新手坑——你在条件判断里误用了赋值运算符=,而非用来做相等判断的===!
咱们来拆解下为什么会出现这种诡异的现象:
- 当你写
if ((signs[counter] = "+"))时,这不是在判断signs[counter]是否等于"+",而是把"+"直接赋值给了signs[counter],并且这个赋值表达式的结果就是"+",在布尔判断里会被视为true。 - 所以不管你原本的
signs[counter]是"/"还是其他符号,第一个if条件都会直接成立,程序会执行加法逻辑,后面的else if分支根本没机会运行。更糟的是,你还把原本的"/"给改成了"+",这就导致除法永远表现得像加法,最终算出8而不是3。
修正后的代码
把所有条件里的=替换成严格相等运算符===(JS里推荐用严格相等来避免隐式类型转换的坑):
for (let e = 1; e < numbers.length; e++) { if (signs[counter] === "+") { newTotal += parseInt(numbers[e]); counter += 1; console.log(newTotal); } else if (signs[counter] === "-") { newTotal -= parseInt(numbers[e]); counter += 1; console.log(newTotal); } else if (signs[counter] === "*") { newTotal *= parseInt(numbers[e]); counter += 1; console.log(newTotal); } else if (signs[counter] === "/") { newTotal = newTotal / parseInt(numbers[e]); counter += 1; console.log(newTotal); } }
修改后每个条件都会正确匹配对应的运算符,除法逻辑就能正常执行,结果也会变成预期的3。
另外给你个小优化建议:可以用对象映射来简化一堆if-else的逻辑,代码会更简洁易维护:
const operators = { "+": (a, b) => a + b, "-": (a, b) => a - b, "*": (a, b) => a * b, "/": (a, b) => a / b }; for (let e = 1; e < numbers.length; e++) { const num = parseInt(numbers[e]); newTotal = operators[signs[counter]](newTotal, num); counter += 1; console.log(newTotal); }
内容的提问来源于stack exchange,提问作者Remitto
相关产品推荐
相关产品推荐

