簡體   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