简体   繁体   English

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

[英]split function in JavaScript using multiple numbers

I'm having a little trouble understanding the split function in JavaScript. 我在理解JavaScript中的split函数时遇到了一些麻烦。

I'm trying to get the numbers before and after the operator in a sum. 我试图求和运算符前后的数字。

My code is as follows: 我的代码如下:

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

This all works just fine when I use 1 number, eg 1 + 1, but won't work with 77 + 8. 当我使用1的数字(例如1 + 1)时,这一切都很好,但是对于77 + 8则无法使用。

Could someone help me out on this one so that this also works with two numbers? 有人可以帮我解决这个问题,以便它也可以处理两个数字吗?

Below condition is wrong in case of input "77 + 1" 如果输入“ 77 +1”,则以下条件是错误的

equation.indexOf('+') == 1

in above case indexOf '+' will be 2 instead of 1 在上述情况下,indexOf'+'将是2而不是1

change that line and for other operators as well like below 更改该行以及其他运营商,如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM