JavaScript to implement a simple web calculator

JavaScript to implement a simple web calculator

background

Since I was assigned to a new project team, the project needs to use js, because I have never been exposed to it, so the leader is going to give me a week to learn. Yes, to implement a simple calculator that supports four mixed operations is the homework, so there is this article. Therefore, the main focus of this article is not on html and css. After all, I only know a little bit of fur and have not studied it in depth.

Achieve results

The final page is as shown below. When the mouse clicks the button, the button will change color and you can perform mixed operations.

The top line shows the calculation formula. When you press "=", the calculation result is displayed.

Technology used

The calculator page is drawn using HTML table. The size, color and mouse hover color of the buttons are set by CSS. Clicking the button will display the value and calculation result on the top line. The four mixed operations are done by JS.

Implementation ideas

Here I divided it into three files, one .html, one .css and one .js

1. First, write HTML and CSS to draw the appearance of the web page. I won’t go into details here. If you are interested, you can directly look at the code
2. Then use js's DOM events to add click events to different types of buttons and call different js functions.
At this step, I just wrote a function definition first, mainly to divide the logic clearly, such as what functions should be realized by pressing a certain button, what effects should be displayed, etc., so that the logic of filling in the function later will not be messed up.
3. Finally, implement the js function, that is, complete the four mixed operations. The focus is on how to implement the four mixed operations and display the results.

When displaying the formula and results above, I defined an array of global variables. Every time a button is clicked, the value of the button is pushed into the array, so that the array can be directly thrown over when it is displayed. Another reason for doing this is that when you click the backspace key, it pops up, and when you click the clear key, it directly assigns an empty array to the array variable, which makes the operation easier.

The next important step is to calculate the expression. For example, if we input an expression like 3 * 4.5 - 1=, how do we evaluate it? The method I thought of is to first convert the input array into an infix expression, then convert the infix expression into a postfix expression, and then evaluate the postfix expression.

1. First, through the above array processing, we get an array like this ['3','*','4','.','5','-','1']
2. Convert this array into a string like this: "3*4.5-1"
3. Then process it into a new array ['3','*','4.5','-','1'] with operators and numbers separated
4. After processing, use the stack to convert the infix expression into a postfix expression
5. Use the stack to evaluate the postfix expression and fill the result after =

Since step 4.5 is about the application of stack in data structure, if you are not clear about it, you can review the data structure. Now we have completed it.

Specific implementation code

As mentioned above, we have analyzed enough, so I won’t say much about this, and will go directly to the code

.html files

<!DOCTYPE html>
<html>
    <head>
        <title>calculator</title>
        <link rel="stylesheet" href="calculator.css" >
        <script src="calculator.js"></script>
    </head>

    <body>
        <div>
            <table border="1">
                <thead>
                    <th colspan="4">
                        <input type="text" id="result" disabled>
                    </th>
                </thead>

                <tbody>
                    <tr>
                        <td><button class="operate" onclick="showNumber(this)">(</button></td>
                        <td><button class="operate" onclick="showNumber(this)">)</button></td>
                        <td><button class="operate" onclick="clearOneResult()">←</button></td>
                        <td><button class="operate" onclick="clearResult()">C</button></td>
                    </tr>
                    <tr>
                        <td><button class="calculate" onclick="showNumber(this)">7</button></td>
                        <td><button class="calculate" onclick="showNumber(this)">8</button></td>
                        <td><button class="calculate" onclick="showNumber(this)">9</button></td>
                        <td><button class="operate" onclick="showNumber(this)">*</button></td>
                    </tr>
                    <tr>
                        <td><button class="calculate" onclick="showNumber(this)">4</button></td>
                        <td><button class="calculate" onclick="showNumber(this)">5</button></td>
                        <td><button class="calculate" onclick="showNumber(this)">6</button></td>
                        <td><button class="operate" onclick="showNumber(this)">-</button></td>
                    </tr>
                    <tr>
                        <td><button class="calculate" onclick="showNumber(this)">1</button></td>
                        <td><button class="calculate" onclick="showNumber(this)">2</button></td>
                        <td><button class="calculate" onclick="showNumber(this)">3</button></td>
                        <td><button class="operate" onclick="showNumber(this)">+</button></td>
                    </tr>
                    <tr>
                        <td><button class="calculate" onclick="showNumber(this)">0</button></td>
                        <td><button class="calculate" onclick="showNumber(this)">.</button></td>
                        <td><button class="operate" onclick="showNumber(this)">/</button></td>
                        <td><button class="operate" onclick="showAnswer()">=</button></td>
                    </tr>
                </tbody>         
            </table>
        </div>
    </body>
</html>

.css files

table{
    margin: 20px;
    padding: 1px;
}

th,input{
    height: 120px;
    width: 410px;
    background-color:rgb(233, 232, 232);
    text-align: right;
    font-size: 40px;
}


button{
    height: 100px;
    width: 100px;
    padding: 0px;
    font-size: 30px;
}

th,input,td,button{
    border: 0px;
}

.calculate{
    background-color: rgb(231, 231, 235);
}

.operate{
    color: coral;
}

button:hover{
    background-color: rgb(147, 241, 253);
}

.js file

var result = new Array();
var ops = "+-*/";

function arrToStr(arr) {
    var strResult = "";
    for (var i = 0; i < arr.length; i++) {
        strResult += arr[i];
    }
    return strResult;
}


function showResult() {
    document.getElementById("result").value = arrToStr(result);
}


function showNumber(id) {
    var val = id.innerHTML;
    result.push(val);
    showResult();
}


function showAnswer() {

    var answer = "";
    var str = arrToStr(result);

    var midExpre = strToExpress(str);
    var suffixExpre = midToSuffix(midExpre);
    answer = suffixValue(suffixExpre);

    //console.log(midExpre);
    //console.log(suffixExpre);

    document.getElementById("result").value = str + "=" + answer;

}


function clearResult() {
    result = [];
    showResult();
}


function clearOneResult() {
    result.pop();
    showResult();
}


function strToExpress(str) {

    var textArr = str.split('');
    var newTextArr = [];
    var calTextArr = [];

    for (var i = 0; i < str.length; i++) {
        if (ops.indexOf(str[i]) != -1 ) {
        
            newTextArr.push("|", str[i], "|");
        }
        else if (str[i] == '('){
            newTextArr.push(str[i], "|");
        }
        else if (str[i] == ')'){
            newTextArr.push("|", str[i]);
        }
        else {
            newTextArr.push(textArr[i]);
        }
    }

    calTextArr = newTextArr.join('').split('|');

    return calTextArr;
}


function midToSuffix(midExpre) {

    var opStack = [];
    var suffixExpre = [];

    for (var i = 0; i < midExpre.length; i++) {

        if (ops.indexOf(midExpre[i]) != -1 || midExpre[i] == '(' || midExpre[i] == ')' ) {

            if (midExpre[i] == '(' || opStack[opStack.length - 1] == '(') {
                opStack.push(midExpre[i]);
            }

            else if (midExpre[i] == ')') {
                do {
                    suffixExpre.push(opStack.pop());
                } while (opStack[opStack.length - 1] != '(');
                opStack.pop();
            }
            else if (opStack.length == 0 || Priority(midExpre[i]) > Priority(opStack[opStack.length - 1])) {
                opStack.push(midExpre[i]);
            }
            else {
                do {
                    suffixExpre.push(opStack.pop());
                } while (opStack.length > 0 && Priority(midExpre[i]) <= Priority(opStack[opStack.length - 1]));

                opStack.push(midExpre[i]);
            }
        }

        else {
            suffixExpre.push(midExpre[i]);
        }
    }

    while (opStack.length > 0) {
        suffixExpre.push(opStack.pop());
    }

    return suffixExpre;
}

function Priority(op) {
    var opPri = 0;
    switch (op) {
        case "+":
            opPri = 1;
            break;
        case "-":
            opPri = 1;
            break;
        case "*":
            opPri = 2;
            break;
        case "/":
            opPri = 2;
            break;

    }
    return opPri;
}

function suffixValue(suffixExpre) {
    var calStack = [];

    console.log(suffixExpre);
    for (var i = 0; i < suffixExpre.length; i++) {
        if (ops.indexOf(suffixExpre[i]) != -1) {
            var opRight = Number(calStack.pop());
            var opLeft = Number(calStack.pop());
            var tmpResult = 0;
            switch (suffixExpre[i]) {
                case '+':
                    tmpResult = opLeft + opRight;
                    break;
                case '-':
                    tmpResult = opLeft - opRight;
                    break;
                case '*':
                    tmpResult = opLeft * opRight;
                    break;
                case '/':
                    tmpResult = opLeft / opRight;
                    break;
            }
            calStack.push(tmpResult);
        }
        else {
            calStack.push(suffixExpre[i]);
        }

        console.log(calStack);
    }

    return calStack.pop();
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • js version to realize calculator function
  • Native js to implement a simple calculator
  • Implementing a simple calculator with javascript
  • js to make a simple calculator
  • Writing a web calculator using javascript
  • A simple calculator written in javascript, with a lot of content and practical methods. Recommended
  • js implements a simple calculator
  • Simple js code to realize calculator operation
  • HTML+JS implements simple calculator code (addition, subtraction, multiplication and division)
  • Detailed explanation of the process of realizing calculator function in javascript

<<:  Build a WebRTC video chat in 5 minutes

>>:  A quick solution to accidentally delete MySQL data (MySQL Flashback Tool)

Recommend

VMware12 installs Ubuntu19.04 desktop version (installation tutorial)

1. Experimental description In the virtual machin...

Docker container custom hosts network access operation

Adding the extra_hosts keyword in docker-compose....

Experience in solving tomcat memory overflow problem

Some time ago, I submitted a product version to t...

HTML insert image example (html add image)

Inserting images into HTML requires HTML tags to ...

Example of implementing dashed border with html2canvas

html2canvas is a library that generates canvas fr...

jQuery plugin to achieve seamless carousel

Seamless carousel is a very common effect, and it...

How to create a responsive column chart using CSS Grid layout

I have been playing around with charts for a whil...

How to change the terminal to a beautiful command line prompt in Ubuntu 18

I reinstalled VMware and Ubuntu, but the command ...

Detailed explanation of React setState data update mechanism

Table of contents Why use setState Usage of setSt...

Appreciation of the low-key and elegant web design in black, white and gray

Among classic color combinations, probably no one...

Detailed explanation of Linux index node inode

1. Introduction to inode To understand inode, we ...