簡體   English   中英

如何防止在我的計算器中輸入像 2.2.2 這樣的數字?

[英]How do I prevent the input of a number like 2.2.2 in my calculator?

我一直在使用 OOP 方法開發一個簡單的 JS 計算器。 我正在努力創建一個防止輸入額外小數的修復程序。 例如,用戶可以輸入 3.2.1.5。 理想情況下,該計算器會在求解並返回結果之前在數字計算器屏幕上顯示整個表達式。 考慮到這一點,簡單地阻止用戶添加第二個小數將阻止他們添加(或他們可能選擇的任何運算符)多個小數一起。 我曾考慮在輸入中的運算符上使用 .split() 和 .join() ,但由於要考慮多個運算符,它開始變得復雜。 理想情況下,我想避免使用正則表達式。

const keys = document.querySelector('.calc-buttons');
    keys.addEventListener('click', event => {
        const {target} = event
        const {value} = target
        if(!target.matches('button')){
            return
        }else{
            calculator.parseInput(value)
            //console.log(value)
        }
    })

const calculator = {
    displayText: '0',
    prevTotal: null,

    parseInput(value){
        //have any of the special buttons(AC, decimal, =) been clicked?
        switch(value){
            case '=':
                //calculate answer
                this.calcAnswer(this.displayText)
                break
            case 'AC':
                //clear screen & stored values
                this.clearAll()
                break
            case '.':
                //create decimal
                if(this.displayText == 0){
                    //pass'0.'
                    this.addText('0.')
                }else{
                    //add value to text string
                    this.addText(value)
                }
                break
            default:
                //add value to text string
                this.addText(value)
                break
            
        }
        
    },
    addText(value){
        if(this.displayText == '0'){
            this.displayText = ''
        }else if(this.prevTotal !== null){
            this.displayText = this.prevTotal
            this.prevTotal = null
        }
        //check if previous input is a number
        if(isNaN(+(value)) && isNaN(+(this.displayText))){
            if(isNaN(this.displayText.slice(-1))){
                return
            }
        }else if(value == '.' && this.displayText.slice(-1) == '.'){
            return
        }
        
        this.displayText += value
        //output display text to screen
        this.outputText(this.displayText)
    },
    outputText(text){
        document.querySelector('.screen').value = text
    },
    calcAnswer(equation){
        let result = Function("return " + equation)()
        this.outputText(result)
        //console.log(equation)
        //console.log(result)
        this.prevTotal = result
    },
    clearAll(){
        this.displayText = '0',
        this.prevTotal = null
        this.outputText(this.displayText)
    }
}

函數基於 StepUp 的答案(這是錯誤的 AFAIK;它應該是.length > 2但我還不能評論)

 const hasManySymbols = (str, symbol) => { const firstIndex = str.indexOf(symbol) // find the first occurrence of the symbol if(firstIndex == -1) return false // if there is no first occurrence there are not many symbols return str.indexOf(symbol, firstIndex + 1) != -1 // whether or not there is a second occurrence } const validate = str => hasManySymbols(str, '.') ? 'invalid input' : 'valid input' console.log(validate('1.23')) // "valid input" console.log(validate('1.2.3')) // "invalid input"

我不確定這是更快還是更慢,但我猜理論上它應該更快。

您可以創建一個簡單的函數來避免重復代碼並在函數中隱藏不必要的細節。 此外,它有助於減少卷積。

因此,創建一個函數來檢查輸入的資格,並根據結果通知用戶或刪除最后一個不正確的字符。

功能草圖可能是這樣的:

const hasManySigns = (str, sign) => str.split(sign).length > 2

一個例子:

 const hasManySigns = (str, sign) => str.split(sign).length > 2 let foo = '1.2.3' const validate = str => hasManySigns(str, '.') ? 'incorrect input' : 'correct input' console.log(validate(foo))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM