Using JavaScript to implement a simple web version calculator


Because I was assigned to a new project team, the project needs js. Because I haven't contacted it, the leader is going to give me a week to study. Yes, realizing a simple calculator that supports four mixed operations is an assignment, so I have this article
Therefore, the main focus of this article is not html and css. After all, I only know a little about it and haven't studied it deeply

Realization effect

The final displayed page is shown in the figure below. When the mouse clicks the button, the button will change color, and four mixed operations can be carried out

The upper line displays the calculation formula. When "=" is pressed, the calculation result is displayed

Technology used

The calculator page is drawn using an html table
Key size, color, mouse hover color change are set with css
Click the button to display the value and calculation result on the button in the top line, and complete the four mixed operations. It is done with js

Realization idea

Here I have three files, one html a css one js

  1. First, I wrote html and css and drew the appearance of the web page. I won't elaborate here. If you are interested, you can look at the code directly
  2. Then use js DOM events to add click events to different types of buttons and call different JS functions.
    At the beginning of this step, I just wrote a function definition, mainly to divide the logic first, such as what functions should be realized and what effects should be displayed by pressing a key, and then fill in the function logic so that the logic will not be disordered
  3. Finally, implement js function, that is, complete four mixed operations. Focus on how to realize four mixed operations and display the results
  • When displaying the formula and results above, I defined an array of global variables. Each time I click the key, I will push the value of the key to the array. In this way, I will directly throw the array away when displaying. Another reason for this is that when you click the backspace key, you pop it. When you click the empty key, you directly assign an empty array to the array variable. It will be easier to operate

  • Next, a very important step is to calculate the expression. For example, how to evaluate an expression such as 3 * 4.5 - 1 =. The method I think of is to first turn the input array into an infix expression, then turn the infix expression into a suffix expression, and then evaluate the infix expression

      1. Firstly, such an array is obtained through the above array processing['3','*','4','.','5','-','1']  
      2. Convert this array into a string and change it to "3"*4.5-1"
      3. It is then processed into a new array of operators and numbers  ['3','*','4.5','-','1']  
      4. After processing, the infix expression is changed into a suffix expression by using the stack
      5. Then use the stack to evaluate the suffix expression, and fill in the result=after

Since step 4.5 is the content of stack application in data structure, if you are not clear, you can review the data structure and complete it now

Specific implementation code

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

. html file

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

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

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

. css file

    margin: 20px;
    padding: 1px;

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

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

    border: 0px;

    background-color: rgb(231, 231, 235);

    color: coral;

    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;

function showAnswer() {

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

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


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


function clearResult() {
    result = [];

function clearOneResult() {

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 {

    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] == '(') {

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


        else {

    while (opStack.length > 0) {

    return suffixExpre;

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

    return opPri;

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

    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;
                case '-':
                    tmpResult = opLeft - opRight;
                case '*':
                    tmpResult = opLeft * opRight;
                case '/':
                    tmpResult = opLeft / opRight;
        else {


    return calStack.pop();

Keywords: Javascript data structure

Added by stride-r on Thu, 30 Dec 2021 16:53:29 +0200