繁体   English   中英

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

[英]split function in JavaScript using multiple numbers

我在理解JavaScript中的split函数时遇到了一些麻烦。

我试图求和运算符前后的数字。

我的代码如下:

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

暂无
暂无

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

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