You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:22:56