簡體   English   中英

運算符在 React JS 中的行為異常

[英]Operators behaving strangely in React JS

我的 React 應用程序將“/”字符串與“+”混淆。

  console.log(numbers, signs);

這記錄:

數組 [ "6", "2" ] 數組 [ "/" ]

在此之后,我遍歷數組並應用適當的運算符,如下所示:

  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);
    }

每個運算符都可以正常工作,除了“/”,它總是像“+”一樣。 所以上面的代碼返回 8 而不是 3。什么給出了?

您正在 if 語句的頂部將符號 [counter] 分配給 +。 使用 ===

為了正常工作,您的代碼應如下所示:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM