使用多个数字在JavaScript中分割函数

问题描述:

我在理解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一起工作。

有人可以帮我解决这个问题,这样也可以使用两个数字吗?

下面条件是错误的输入的情况下 “77 + 1”

equation.indexOf('+') == 1 

在上述情况下的indexOf '+' 将是2而不是1

更改,线和用于其他运营商也如下

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

感谢您的解释。这真的帮了我:D – Chris

+0

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