2015-12-02 48 views
0

我在理解JavaScript中的分割函數時遇到了一些麻煩。使用多個數字在JavaScript中分割函數

我試圖在運算符之前和之後得到數字。

我的代碼如下:

else if(btnVal == '=') { 
      var equation = inputVal; 
      var lastChar = equation[equation.length - 1]; 

      // Replace all instances of x with * respectively. 
      equation = equation.replace(/x/g, '*'); 

      if (operators.indexOf(lastChar) > -1 || lastChar == ',') 
       equation = equation.replace(/.$/, ''); 

      if (equation) 
       if (equation.indexOf('+') == 1) { 

        var firstNumber = equation.split('+')[0]; 
        var secondNumber = equation.split('+')[1]; 

        var result = Number(firstNumber) + Number(secondNumber); 

        input.innerHTML = result; 

       } 
       else if (equation.indexOf('*') == 1) { 
        firstNumber = equation.split('*')[0]; 
        secondNumber = equation.split('*')[1]; 

        result = Number(firstNumber) * Number(secondNumber); 

        input.innerHTML = result; 
       } 
       else if (equation.indexOf('-') == 1) { 
        firstNumber = equation.split('-')[0]; 
        secondNumber = equation.split('-')[1]; 

        result = Number(firstNumber) - Number(secondNumber); 

        input.innerHTML = result; 
       } 
       else if (equation.indexOf('/') == 1) { 
        firstNumber = equation.split('/')[0]; 
        secondNumber = equation.split('/')[1]; 

        result = Number(firstNumber)/Number(secondNumber); 

        input.innerHTML = result; 
       } 

      decimalAdded = false; 
     } 

這一切工作就好了,當我用1號,例如1 + 1,但不會與77 + 8一起工作。

有人可以幫我解決這個問題,這樣也可以使用兩個數字嗎?

回答

4

下面條件是錯誤的輸入的情況下 「77 + 1」

equation.indexOf('+') == 1 

在上述情況下的indexOf '+' 將是2而不是1

更改,線和用於其他運營商也如下

equation.indexOf('+') != -1 
+0

感謝您的解釋。這真的幫了我:D – Chris

+0

@Chris你能接受答案嗎? – Murli