Table of Contents
precautions for implementing the calculator function with JavaScript? The following is a practical case. Let’s take a look. one time. " >This time I will show you how to implement the calculator function with JavaScript. What are the precautions for implementing the calculator function with JavaScript? The following is a practical case. Let’s take a look. one time.
Home Web Front-end JS Tutorial How to implement calculator function in javascript

How to implement calculator function in javascript

May 23, 2018 am 11:34 AM
javascript js calculator


This time I will show you how to implement the calculator function with JavaScript. What are the precautions for implementing the calculator function with JavaScript? The following is a practical case. Let’s take a look. one time.

This computer mainly stores it in an array through a two-dimensional array, and then uses functions to control the displayed effect. Some keys occupy two columns. The colspan function is used to merge the two columns. First, the outside of the entire computer is After the style is designed, the main implementation code and renderings are as follows:

How to implement calculator function in javascript


var btns=[
            [
                {text:"AC",id:"btn_C",value:"c",col:1},
                {text:"Del",id:"btn_JJ",value:"✘",col:1},
                {text:"%",id:"btn_BF",value:"%",col:1},
                {text:"÷",id:"btn_CY",value:"/",col:1,cls:"yellow"},
            ],
            [
                {text:"7",id:"btn_C",value:"7",col:1},
                {text:"8",id:"btn_JJ",value:"8",col:1},
                {text:"9",id:"btn_BF",value:"9",col:1},
                {text:"×",id:"btn_CY",value:"*",col:1,cls:"yellow"},
            ],
            [
                {text:"4",id:"btn_C",value:"4",col:1},
                {text:"5",id:"btn_JJ",value:"5",col:1},
                {text:"6",id:"btn_BF",value:"6",col:1},
                {text:"-",id:"btn_CY",value:"-",col:1,cls:"yellow"},
            ],
            [
                {text:"1",id:"btn_C",value:"1",col:1},
                {text:"2",id:"btn_JJ",value:"2",col:1},
                {text:"3",id:"btn_BF",value:"3",col:1},
                {text:"+",id:"btn_CY",value:"+",col:1,cls:"yellow"},
            ],
            [
                {text:"0",id:"btn_C",value:"0",col:2},
                {text:".",id:"btn_JJ",value:".",col:1},
                {text:"=",id:"btn_BF",value:"=",col:1,cls:"gray"},
            ],
            ];
            function creatUI(config){
                var html=[];                
                for(var i=0,len=config.length;i<len;i++){
                    html.push("<tr>");
                    var arry=config[i];                    
                    for(var j=0;j<arry.length;j++)
                    {
                        var obj=arry[j];
                        html.push("<td colspan="+obj.col+" class=&#39;"+obj.cls+"&#39; v=&#39;"+obj.value+"&#39;>"+obj.text+"</td>");
                    }
                    html.push("</tr>");
                }
            var b = document.getElementById("tbody");
                b.innerHTML=html.join("");
            }
            creatUI(btns);
Copy after login

The main code for the entire calculator implementation is to add Click the event and save it in an array. Create some functions to determine whether the currently input value meets the calculation requirements. If so, pass the array value to the eval() function, calculate the result through this function, and pass the result to the display. The corresponding p is displayed to the user through innerText. As long as the implementation code is as follows:

function register(){

                var container=document.getElementById("content");
                var tds=document.getElementsByTagName("td");
                var show=document.getElementById("show");                
                for(var i=0,len=tds.length;i<len;i++)
                {
                    var block=tds[i];                    
                    block.onclick=function(){

                        var v=this.getAttribute("v");                        
                        //实现清零功能
                        if(v=="c"){
                            ac();                            
                            show.innerText="0";                            
                            return ;
                        }                        
                        inputs.push(v);                        
                        //实现删除功能
                        if(v=="✘"){                            
                        if(inputs.length==0||inputs.length==1)
                            {                                
                            inputs.length=0;                                
                            show.innerText=&#39;0&#39;;
                            }                           
                             else{                                
                             inputs.length=inputs.length-2;
                            }
                        }                        
                        //检测是不是相邻两个是不是操作符
                        checkNeiber();                        
                        //调用回显的函数
                        echoEcho(show);                        
                        //检测如果已经有两个运算符的话,直接进行计算
                        if(isStartCompute()){
                            var result=eval(inputs.join(""));                            
                            inputs.length=0;
                            inputs[0]=result;                            
                            show.innerText=result;
                            inputs[1]=temp;                            
                            //show.innerText=result;
                        }                        
                        //如果输入等号,直接让其输出结果
                        if(v==&#39;=&#39;)
                        {                            
                        if(inputs.length==1)
                            {                                
                            inputs.length=0;                                
                            show.innerText=0;   
                            }                            
                            else{                                
                            inputs.length=inputs.length-1;
                                var result=eval(inputs.join(""));                                
                                inputs.length=0;
                                inputs[0]=result;                                
                                show.innerText=result;                                
                                inputs.length=0;
                            }
                        }

                    }
                }
            }
Copy after login

The remaining functions are to determine whether the calculator can perform calculations. There are many pitfalls in the function. Please pay attention. I Show everyone the effect of using this calculator:

How to implement calculator function in javascript

How to implement calculator function in javascript

##All the codes for the entire calculator implementation are as follows:

<!DOCTYPE html><html>
    <head>
        <meta charset="UTF-8">
        <title>简单的计算器</title>
        <style type="text/css">
            *{                
            margin: 0px;                
            padding: 0px;            
            }
            .mytable{                
            border: 1px solid black;                
            border-spacing: 0px;                
            margin: 0 auto; 

            }
            .mytable td{                
            border: 1px solid black;                
            padding: 20px;                
            text-align: center;                
            vertical-align: middle;                
            cursor:pointer !important;            
            }
            td:hover{                
            background-color: lightsteelblue;            
            }
            #content{                
            font-size: 20px;                
            margin: 0 auto; 
                width:262px;                
                background-color:white;            
                }
            .screen{                
            height: 80px;                
            padding-right: 8px;                
            background-color:rgb(112,131,147);                
            opacity: 0.8;                
            text-align: right;                
            line-height:80px;                
            font-size: 40px;                
            overflow: hidden;            
            }
            .yellow{                
            background-color:rgb(255,152,62);            
            }
            .gray{                
            background-color: #808080;           
             }
        </style>
    </head>
    <body>
        <p id="content">
            <p class="screen" id="show">0</p>
            <p class="btns">
                <table class="mytable">
                    <tbody id="tbody">

                    </tbody>
                </table>
            </p>
        </p>
        <script type="text/javascript">
            var btns=[
            [
                {text:"AC",id:"btn_C",value:"c",col:1},
                {text:"Del",id:"btn_JJ",value:"✘",col:1},
                {text:"%",id:"btn_BF",value:"%",col:1},
                {text:"÷",id:"btn_CY",value:"/",col:1,cls:"yellow"},
            ],
            [
                {text:"7",id:"btn_C",value:"7",col:1},
                {text:"8",id:"btn_JJ",value:"8",col:1},
                {text:"9",id:"btn_BF",value:"9",col:1},
                {text:"×",id:"btn_CY",value:"*",col:1,cls:"yellow"},
            ],
            [
                {text:"4",id:"btn_C",value:"4",col:1},
                {text:"5",id:"btn_JJ",value:"5",col:1},
                {text:"6",id:"btn_BF",value:"6",col:1},
                {text:"-",id:"btn_CY",value:"-",col:1,cls:"yellow"},
            ],
            [
                {text:"1",id:"btn_C",value:"1",col:1},
                {text:"2",id:"btn_JJ",value:"2",col:1},
                {text:"3",id:"btn_BF",value:"3",col:1},
                {text:"+",id:"btn_CY",value:"+",col:1,cls:"yellow"},
            ],
            [
                {text:"0",id:"btn_C",value:"0",col:2},
                {text:".",id:"btn_JJ",value:".",col:1},
                {text:"=",id:"btn_BF",value:"=",col:1,cls:"gray"},
            ],
            ];            
            function creatUI(config){
                var html=[];                
                for(var i=0,len=config.length;i<len;i++){
                    html.push("<tr>");                    
                    var arry=config[i];                    
                    for(var j=0;j<arry.length;j++)
                    {                        
                    var obj=arry[j];
                        html.push("<td colspan="+obj.col+" class=&#39;"+obj.cls+"&#39; v=&#39;"+obj.value+"&#39;>"+obj.text+"</td>");
                    }
                    html.push("</tr>");
                }            var b = document.getElementById("tbody");
                b.innerHTML=html.join("");
            }
            creatUI(btns);            //注册点击事件
            var inputs=[];//定义用户输入按钮的数组

            function register(){

                var container=document.getElementById("content");                
                var tds=document.getElementsByTagName("td");                
                var show=document.getElementById("show");                
                for(var i=0,len=tds.length;i<len;i++)
                {                    var block=tds[i];
                    block.onclick=function(){

                        var v=this.getAttribute("v");                        
                        //实现清零功能
                        if(v=="c"){
                            ac();
                            show.innerText="0";                            
                            return ;
                        }
                        inputs.push(v);                        
                        //实现删除功能
                        if(v=="✘"){                            
                        if(inputs.length==0||inputs.length==1)
                            {
                                inputs.length=0;
                                show.innerText=&#39;0&#39;;
                            }                            
                            else{
                                inputs.length=inputs.length-2;
                            }
                        }                        
                        //检测是不是相邻两个是不是操作符
                        checkNeiber();                        
                        //调用回显的函数
                        echoEcho(show);                        
                        //检测如果已经有两个运算符的话,直接进行计算
                        if(isStartCompute()){                            
                        var result=eval(inputs.join(""));
                            inputs.length=0;
                            inputs[0]=result;
                            show.innerText=result;
                            inputs[1]=temp;                            
                            //show.innerText=result;
                        }                        
                        //如果输入等号,直接让其输出结果
                        if(v==&#39;=&#39;)
                        {                            
                        if(inputs.length==1)
                            {
                                inputs.length=0;
                                show.innerText=0;   
                            }                            else{
                                inputs.length=inputs.length-1;                                
                                var result=eval(inputs.join(""));
                                inputs.length=0;
                                inputs[0]=result;
                                show.innerText=result;
                                inputs.length=0;
                            }
                        }

                    }
                }
            }            //检测到两个操作符的时候,就进行计算
            function isStartCompute(){
                var ctn=0;                
                for(var i=0;i<inputs.length;i++){                    
                var ip=inputs[i];                    
                if(ip=="+"||ip=="-"||ip=="*"||ip=="/"||ip=="%")
                    {
                        ctn++;
                    }                    if(ctn>=2)
                    {
                        temp=inputs[i];
                        inputs.length=inputs.length-1;                        return true;
                    }                    if(ip=="=" && checkNumber(inputs[i+1])){                        
                    var num=inputs[i+1];
                        inputs.length=0;
                        inputs[0]=num;                        
                        return true;
                    }
                }
            }            //判断如果是两个相邻的操作符的情况
            function checkNeiber(){
                for(var i=0;i<inputs.length;i++)
                {                    
                if((inputs[i]=="+"||inputs[i]=="-"||inputs[i]=="*"||inputs[i]=="/"||inputs[i]=="%"||inputs[i]=="=")&&(inputs[i+1]=="+"||inputs[i+1]=="-"||inputs[i+1]=="*"||inputs[i+1]=="/"||inputs[i+1]=="%"||inputs[i+1]=="="))
                    {                        
                    var lastKey=inputs[i+1];
                        inputs.length=inputs.length-2;
                        inputs.push(lastKey);                        
                        return ;
                    }
                }
            }   
            function checkNumber(word){
                word=parseInt(word);                
                if(word>0 && word<9){                    
                return true;
                }
            }            //清零功能
            function ac(){
                inputs.length=0;
                echoEcho();
            }            //增加回显功能
            function echoEcho(showl){
                if(!showl){
                    showl=document.getElementById("show");
                }                if(inputs.length==0){
                    showl.innerText="0";        
                }
                showl.innerText =inputs.join("");
            }
            window.onload = function(){
                register();
            }        </script>
    </body></html>
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of command pattern of JS design pattern

What are the differences between call, apply and bind in javascript

The above is the detailed content of How to implement calculator function in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

An efficient Fibonacci sequence calculator written in PHP An efficient Fibonacci sequence calculator written in PHP Mar 21, 2024 am 10:06 AM

Efficient Fibonacci sequence calculator: PHP implementation of Fibonacci sequence is a very classic mathematical problem. The rule is that each number is equal to the sum of the previous two numbers, that is, F(n)=F(n -1)+F(n-2), where F(0)=0 and F(1)=1. When calculating the Fibonacci sequence, it can be implemented recursively, but performance problems will occur as the value increases. Therefore, this article will introduce how to write an efficient Fibonacci using PHP

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles