7 Ways JS achieve a simple calculator

First put Figure (Okay compare frustration)

Method One: the easiest version

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>简易计算器</title>
<style>
    body {
        background-color: #eee;
    }
    #calculator {
        margin: 100px 0 0 150px;
    }
</style>
</head>
<body>

<!-- 简易计算器 -->
<div id="calculator">
    <p>
        <input type="text" class="formerInput" value="1" />
        <span class="sign">+</span>
        <input type="text" class="laterInput" value="1" />
        <span>=</span>
        <span class="resultOutput">2</span>
    </p>
    <p>

        
         resultOutput = calculator.querySelector('.resultOutput');

        //
        function addHandler() {
            sign.innerHTML = '+';
            resultOutput.innerHTML = +formerInput.value + +laterInput.value;
        }
        //
        function subtractHandler() {
            sign.innerHTML = '-';
            resultOutput.innerHTML = formerInput.value - laterInput.value;
        }
        //
        function multiplyHandler() {
            sign.innerHTML = '×';
            resultOutput.innerHTML = formerInput.value * laterInput.value;
        }
        //
        function divideHandler() {
            sign.innerHTML = '÷';
            resultOutput.innerHTML = formerInput.value / laterInput.value;
        }
</script>
</body>
</html>

Method II: Separation Structure and Behavior

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>简易计算器</title>
<style>
    body {
        background-color: #eee;
    }
    #calculator {
        margin: 100px 0 0 150px;
    }
</style>
</head>
<body>

<!-- 简易计算器 -->
<div id="calculator">
    <p>
        <input type="text" class="formerInput" value="1" />
        <span class="sign">+</span>
        <input type="text" class="laterInput" value="1" />
        <span>=</span>
        <span class="resultOutput">2</span>
    </p>
    <p>

        
         resultOutput = calculator.querySelector('.resultOutput');
        var btns = calculator.querySelectorAll('.btn');

        // 绑定事件
        // +
        btns[0].onclick = addHandler;
        // -
        btns[1].onclick = subtractHandler;
        // ×
        btns[2].onclick = multiplyHandler;
        // ÷
        btns[3].onclick = divideHandler;

        //
        function addHandler() {
            sign.innerHTML = '+';
            resultOutput.innerHTML = +formerInput.value + +laterInput.value;
        }
        //
        function subtractHandler() {
            sign.innerHTML = '-';
            resultOutput.innerHTML = formerInput.value - laterInput.value;
        }
        //
        function multiplyHandler() {
            sign.innerHTML = '×';
            resultOutput.innerHTML = formerInput.value * laterInput.value;
        }
        //
        function divideHandler() {
            sign.innerHTML = '÷';
            resultOutput.innerHTML = formerInput.value / laterInput.value;
        }
</script>
</body>
</html>

Method three: cycling binding events

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>简易计算器</title>
<style>
    body {
        background-color: #eee;
    }
    #calculator {
        margin: 100px 0 0 150px;
    }
</style>
</head>
<body>

<!-- 简易计算器 -->
<div id="calculator">
    <p>
        <input type="text" class="formerInput" value="1" />
        <span class="sign">+</span>
        <input type="text" class="laterInput" value="1" />
        <span>=</span>
        <span class="resultOutput">2</span>
    </p>
    <p>

        
         resultOutput = calculator.querySelector('.resultOutput');
        var btns = calculator.querySelectorAll('.btn');

        // 绑定事件
        for (var i = 0; i < btns.length; i++) {
            btns[i].onclick = function () {
                switch (this.title) {
                    case 'add':
                        addHandler();
                        break;
                    case 'subtract':
                        subtractHandler();
                        break;
                    case 'multiply':
                        multiplyHandler();
                        break;
                    case 'divide':
                        divideHandler();
                        break;
                }
            };
        }

        //
        function addHandler() {
            sign.innerHTML = '+';
            resultOutput.innerHTML = +formerInput.value + +laterInput.value;
        }
        //
        function subtractHandler() {
            sign.innerHTML = '-';
            resultOutput.innerHTML = formerInput.value - laterInput.value;
        }
        //
        function multiplyHandler() {
            sign.innerHTML = '×';
            resultOutput.innerHTML = formerInput.value * laterInput.value;
        }
        //
        function divideHandler() {
            sign.innerHTML = '÷';
            resultOutput.innerHTML = formerInput.value / laterInput.value;
        }
</script>
</body>
</html>

Method four: extraction function

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>简易计算器</title>
<style>
    body {
        background-color: #eee;
    }
    #calculator {
        margin: 100px 0 0 150px;
    }
</style>
</head>
<body>

<!-- 简易计算器 -->
<div id="calculator">
    <p>
        <input type="text" class="formerInput" value="1" />
        <span class="sign">+</span>
        <input type="text" class="laterInput" value="1" />
        <span>=</span>
        <span class="resultOutput">2</span>
    </p>
    <p>
        <input type="button" value="+" class="btn" title="add" />
        <input type="button" value="-" class="btn" title="subtract" />
        <input type="button" value="×" class="btn" title="multiply" />
        <input type="button" value="÷" class="btn" title="divide" />
    </p>
</div>

<script>
        // 获取元素
        var calculator = document.querySelector('#calculator');
        var formerInput = calculator.querySelector('.formerInput');
        var laterInput = calculator.querySelector('.laterInput');
        var sign = calculator.querySelector('.sign');
        var resultOutput = calculator.querySelector('.resultOutput');
        var btns = calculator.querySelectorAll('.btn');

        // 绑定事件
        each(btns, function (index, elem ) {
            elem.onclick = function () {
                switch (this.title) {
                    case 'add':
                        addHandler();
                        break;
                    case 'subtract':
                        subtractHandler();
                        break;
                    case 'multiply':
                        multiplyHandler();
                        break;
                    case 'divide':
                        divideHandler();
                        break;
                }
            };
        });
        
        // 遍历
        function each(array, fn) {
            for (var i = 0; i < array.length; i++) {
                fn(i, array[i]);
            }
        }

        // 更新符号
        function updateSign(symbol) {
            sign.innerHTML = symbol;
        }

        // adder 
        function the Add (num1, num2) {
             return + + + num1 num2; 
        } 
        // subtraction 
        function Subtract (num1, num2) {
             return num1 - num2; 
        } 
        // multiplication 
        function Multiply (num1, num2) {
             return num1 * num2; 
        } 
        // divide 
        function divide (num1, num2) {
             return num1 / num2; 
        } 

        // output 
        function outputResult (result) { 
            resultOutput.innerHTML = result;
        }

        //
        function addHandler() {
            // sign.innerHTML = '+';
            updateSign('+');
            outputResult(add(formerInput.value, laterInput.value));
        }
        //
        function subtractHandler() {
            updateSign('-');
            outputResult(subtract(formerInput.value, laterInput.value));
        }
        //
        function multiplyHandler() {
            updateSign('×');
            outputResult(multiply(formerInput.value, laterInput.value));
        }
        //
        function divideHandler() {
            updateSign('÷');
            outputResult(divide(formerInput.value, laterInput.value));
        }
</script>
</body>
</html>

Method five: management code ( found Organization)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>简易计算器</title>
<style>
    body {
        background-color: #eee;
    }
    #calculator {
        margin: 100px 0 0 150px;
    }
</style>
</head>
<body>

<!-- 简易计算器 -->
<div id="calculator">
    <p>
        <input type="text" class="formerInput" value="1" />
        <span class="sign">+</span>
        <input type="text" class="laterInput" value="1" />
        <span>=</span>
        <span class="resultOutput">2</span>
    </p>
    <p>
        <input type="button" value="+" class="btn" title="add" />
        <input type="button" value="-" class="btn" title="subtract" />
        <input type="button" value="×" class="btn" title="multiply" />
        <input type="button" value="÷" class="btn" title="divide" />
    </p>
</div>

<script>
            // 获取元素
            var wrapElem = document.querySelector('#calculator');
            var calculatorElem = {
                formerInput: wrapElem.querySelector('.formerInput'),
                laterInput: wrapElem.querySelector('.laterInput'),
                sign: wrapElem.querySelector('.sign'),
                resultOutput: wrapElem.querySelector('.resultOutput'),
                btns: wrapElem.querySelectorAll('.btn')
            };

            // 绑定事件
            each(calculatorElem.btns, function (index, elem    ) {
                elem.onclick = function () {
                    switch (this.title) {
                        case 'add':
                            addHandler();
                            break;
                        case 'subtract':
                            subtractHandler();
                            break;
                        case 'multiply':
                            multiplyHandler();
                            break;
                        case 'divide':
                            divideHandler();
                            break;
                    }
                };
            });
            
            // 遍历
            function each(array, fn) {
                for (var i = 0; i < array.length; i++) {
                    fn(i, array[i]);
                }
            }

            // 更新符号
            function updateSign(symbol) {
                calculatorElem.sign.innerHTML = symbol;
            }

            var operation = {
                add: function(num1, num2) {
                    return +num1 + +num2;
                },
            subtract: function(num1, num2) {
                    return num1 - num2;
                },
            multiply: function(num1, num2) {
                    return num1 * num2;
                },
            divide: function(num1, num2) {
                    return num1 / num2;
                }
            };

            // 输出结果
            function outputResult(result) {
                calculatorElem.resultOutput.innerHTML = result;
            }

            //
            function addHandler() {
                // sign.innerHTML = '+';
                updateSign('+');
                outputResult(operation.add(calculatorElem.formerInput.value, calculatorElem.laterInput.value));
            }
            //
            function subtractHandler() {
                updateSign('-');
                outputResult(operation.subtract(calculatorElem.formerInput.value, calculatorElem.laterInput.value));
            }
            //
            function multiplyHandler() {
                updateSign('×');
                outputResult(operation.multiply(calculatorElem.formerInput.value, calculatorElem.laterInput.value));
            }
            //
            function divideHandler() {
                updateSign('÷');
                outputResult(operation.divide(calculatorElem.formerInput.value, calculatorElem.laterInput.value));
            }
</script>
</body>
</html>

Method six: OCP Open - Closed Principle

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>简易计算器</title>
<style>
    body {
        background-color: #eee;
    }
    #calculator {
        margin: 100px 0 0 150px;
    }
</style>
</head>
<body>

<!-- 简易计算器 -->
<div id="calculator">
    <p>
        <input type="text" class="formerInput" value="1" />
        <span class="sign">+</span>
        <input type="text" class="laterInput" value="1" />
        <span>=</span>
        <span class="resultOutput">2</span>
    </p>
    <p>
        <input type="button" value="+" class="btn" title="add" />
        <input type="button" value="-" class="btn" title="subtract" />
        <input type="button" value="×" class="btn" title="multiply" />
        <input type="button" value="÷" class="btn" title="divide" />
        <input type="button" value="%" class="btn" title="mod" />
        <input type="button" value="^" class="btn" title="power" />
        <!-- <input type="button" value="1/x" class="btn" title="invert" /> -->
    </p>
</div>

<script>
    // 获取元素
    var wrapElem = document.querySelector('#calculator');
    var calculatorElem = {
        formerInput: wrapElem.querySelector('.formerInput'),
        laterInput: wrapElem.querySelector('.laterInput'),
        sign: wrapElem.querySelector('.sign'),
        resultOutput: wrapElem.querySelector('.resultOutput'),
        btns: wrapElem.querySelectorAll('.btn')
    };

    // 绑定事件
    each(calculatorElem.btns, function (index, elem    ) {
            elem.onclick = function () {
                updateSign(this.value);
                outputResult(operate(this.title, calculatorElem.formerInput.value, calculatorElem.laterInput.value));
            };
    });
    
    // 遍历
    function each(array, fn) {
        for (var i = 0; i < array.length; i++) {
            fn(i, array[i]);
        }
    }

    // 更新符号
    function updateSign(symbol) {
        calculatorElem.sign.innerHTML = symbol;
    }

    // 运算
    function operate(name, num1, num2) {
            if (!operation[name]) throw newError ( 'name does not exist' + name + 'operation method!' );
             Return Operation [name] (num1, num2); 
    } 

    var Operation = { 
        the Add: function (num1, num2) {
             return + + + num1 num2 ; 
        }, 
        Subtract: function (num1, num2) {
                 return num1 - num2; 
            }, 
        Multiply: function (num1, num2) {
                 return num1 * num2; 
            }, 
        Divide: function (num1, num2) {
                return num1 / num2;
            },
            addOperation: function (name, fn) {
                if (!this[name]) {
                    this[name] = fn;
                }
                return this;
            }
    };

    operation.addOperation('mod', function (num1, num2) {
        return num1 % num2;
    }).addOperation('power', function (base, power) {
        return Math.pow(base, power);
    });

    // 输出结果
    function outputResult(result) {
        calculatorElem.resultOutput.innerHTML = result;
    }
</script>
</body>
</html>

Seven: Modular

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>简易计算器</title>
<style>
    body {
        background-color: #eee;
    }
    #calculator {
        margin: 100px 0 0 150px;
    }
</style>
</head>
<body>

<!-- 简易计算器 -->
<div id="calculator">
    <p>
        <input type="text" class="formerInput" value="1" />
        <span class="sign">+</span>
        <input type="text"class="laterInput" value="1" />
        <span>=</span>
        <span class="resultOutput">2</span>
    </p>
    <p>
        <input type="button" value="+" class="btn" title="add" />
        <input type="button" value="-" class="btn" title="subtract" />
        <input type="button" value="×" class="btn" title="multiply" />
        <input type="button" value="÷" class="btn" title="divide" />
        <input type="button" value="%" class="btn" title="mod" />
        <input type="button" value="^" class="btn" title="power" />
        <input type="button" value="1/x" class="btn" title="invert" />
    </p>
</div>

<script>

    (function () {
        // 获取元素
        var wrapElem = document.querySelector('#calculator');
        var calculatorElem = {
            formerInput: wrapElem.querySelector('.formerInput'),
            laterInput: wrapElem.querySelector('.laterInput'),
            sign: wrapElem.querySelector('.sign'),
            resultOutput: wrapElem.querySelector('.resultOutput'),
            btns: wrapElem.querySelectorAll('.btn')
        };

        // 绑定事件
        each(calculatorElem.btns, function (index, elem    ) {
                elem.onclick = function () {
                    updateSign(this.value);
                    outputResult(operate(this.title, calculatorElem.formerInput.value, calculatorElem.laterInput.value));
                };
        });
        
        // 遍历
        function each(array, fn) {
            for (var i = 0; i < array.length; i++) {
                fn(i, array[i]);
            }
        }

        // 更新符号
        function updateSign(symbol) {
            calculatorElem.sign.innerHTML = symbol;
        }

        // 运算
        var operate = (function () {
                var operation = {
                    add: function(num1, num2) {
                        return +num1 + +num2;
                    },
                subtract: function(num1, num2) {
                        return num1 - num2;
                    },
                multiply: function(num1, num2) {
                        return num1 * num2;
                    },
                divide: function(num1, num2) {
                         return num1 /  num2;
                   }, 
                   addOperation: function (name, Fn) {
                         IF (! {Operation [name]) 
                            Operation [name] = Fn; 
                        } 
                        return Operation; 
                    } 
            }; 

            function Operate (name) {
                     IF (! operation [name]) the throw  new new Error ( 'name does not exist' + name + 'operation method!' );
                     return operation[name].apply(operation, [].slice.call(arguments, 1, arguments.length));
            }
            operate.addOperation = operation.addOperation;

            return operate;
        })();

        operate.addOperation('mod', function (num1, num2) {
            return num1 % num2;
        }).addOperation('power', function (base, power) {
            return Math.pow(base, power);
        }).addOperation('invert', function (num) {
            return 1 / num;
        });

        // 输出结果
        function outputResult(result) {
            calculatorElem.resultOutput.innerHTML = result;
        }
    })();
      
</script>
</body>
</html>

Guess you like

Origin www.cnblogs.com/chenyingying0/p/12143674.html