使用多个数字的JavaScript中的split函数

split function in JavaScript using multiple numbers

本文关键字:JavaScript 中的 split 函数 数字      更新时间:2023-09-26

我在理解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