[英]Operators behaving strangely in React JS
My React app is confusing a "/" string with "+".我的 React 应用程序将“/”字符串与“+”混淆。
console.log(numbers, signs);
This logs:这记录:
Array [ "6", "2" ] Array [ "/" ]
数组 [ "6", "2" ] 数组 [ "/" ]
After this I iterate over the arrays and apply the appropriate operator, as shown below:在此之后,我遍历数组并应用适当的运算符,如下所示:
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);
}
Every operator works fine, except for "/", which always acts like "+".每个运算符都可以正常工作,除了“/”,它总是像“+”一样。 So the above code returns 8 instead of 3. What gives?
所以上面的代码返回 8 而不是 3。什么给出了?
you are assigning signs[counter] to + on top of your if statement.您正在 if 语句的顶部将符号 [counter] 分配给 +。 use ===
使用 ===
In order to work properly your code should be like below:为了正常工作,您的代码应如下所示:
let counter = 0;
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.