JavaScript实现简单计算器


Posted in Javascript onMarch 19, 2020

适合初学者参考的简易计算器,里面没有太多的难以理解的方法,使用的是最基础的JS语法解决式子的运算问题,同时处理了式子中的运算优先级。

实现思路

1、通过绑定点击事件实现待计算式子的输入
2、遍历原式子,读取式子中乘除运算符的位置
3、优先处理乘除取余运算
4、处理加减运算
5、返回结果

代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
 <!-- 计算器 -->
 <style>
    .work2{
      width: 500px;
      margin-top: 50px;
    }
    h2{
      color: #333;
    }
    #work2Article1{
      width: 100%;
      height: 200px;
      background: #cccccc;
      font-size: 20px;
    }
    #work2Article2{
      width: 100%;
      height: 400px;
      background: #cccccc;
    }
    #work2Article2 button{
      width: 24.1%;
      height: 20%;
      color: #333;
      background: #999;
    }
    .work2 button{
      font-size: 20px;
    }
    
  </style>
  <section class="work2">
    <h2>计算器</h2>
    <article id="work2Article1">
  
    </article>
    <article id="work2Article2">
      <button id="work2BtnCle">AC</button>
      <button id="work2BtnDel">×</button>
      <button id="work2BtnRem">%</button>
      <button id="work2BtnDiv">/</button>
      <button id="work2Btn7">7</button>
      <button id="work2Btn8">8</button>
      <button id="work2Btn9">9</button>
      <button id="work2BtnMul">*</button>
      <button id="work2Btn4">4</button>
      <button id="work2Btn5">5</button>
      <button id="work2Btn6">6</button>
      <button id="work2BtnSub">-</button>
      <button id="work2Btn1">1</button>
      <button id="work2Btn2">2</button>
      <button id="work2Btn3">3</button>
      <button id="work2BtnAdd">+</button>
      <button id="work2BtnNull">未开发</button>
      <button id="work2Btn0">0</button>
      <button id="work2BtnPoi">.</button>
      <button id="work2BtnEqu">=</button>
    </article>
  </section>
    
  <script>
    
    var num = "0";         //输入的原式
    var res = 0 ;          //结果

    var work2Article1 = document.getElementById('work2Article1');

    var work2BtnCle = document.getElementById('work2BtnCle');
    var work2BtnDiv = document.getElementById('work2BtnDiv');
    var work2BtnDel = document.getElementById('work2BtnDel');
    var work2BtnRem = document.getElementById('work2BtnRem');
    var work2BtnMul = document.getElementById('work2BtnMul');
    var work2BtnSub = document.getElementById('work2BtnSub');
    var work2BtnAdd = document.getElementById('work2BtnAdd');
    var work2BtnNull = document.getElementById('work2BtnNull');
    var work2BtnPoi = document.getElementById('work2BtnPoi');
    var work2BtnEqu = document.getElementById('work2BtnEqu');
    
    var work2Btn1 = document.getElementById('work2Btn1');
    var work2Btn2 = document.getElementById('work2Btn2');
    var work2Btn3 = document.getElementById('work2Btn3');
    var work2Btn4 = document.getElementById('work2Btn4');
    var work2Btn5 = document.getElementById('work2Btn5');
    var work2Btn6 = document.getElementById('work2Btn6');
    var work2Btn7 = document.getElementById('work2Btn7');
    var work2Btn8 = document.getElementById('work2Btn8');
    var work2Btn9 = document.getElementById('work2Btn9');
    var work2Btn0 = document.getElementById('work2Btn0');
    
    // 初始化
    work2BtnCle.onclick = function () {
      num = "0" ;
      work2Article1.innerText=`${num}`;
    }
   
    work2BtnDel.onclick = function () {
      // 判断原式长度,长度为1时变为0
      if(num.length==1){
        num = '0' ;
        work2Article1.innerText=num;
        // 否则减去最后一位
      }else{
        num = num.substring(0,num.length-1);
        work2Article1.innerText=num;
      }
    }
    // 运算符点击事件
    work2BtnDiv.onclick = function () {
      num += "/" 
      work2Article1.innerText=num;
    }
    work2BtnRem.onclick = function () {
      num += "%" ; 
      work2Article1.innerText=`${num}`;
    }
    work2BtnMul.onclick = function () {
      num += "*" ; 
      work2Article1.innerText=`${num}`;
    }
    work2BtnAdd.onclick = function () {
      num += "+" ; 
      work2Article1.innerText=`${num}`;
    }
    work2BtnNull.onclick = function () {
      alert('下次一定开发出来');
    }
    work2BtnPoi.onclick = function () {
      num += "." ; 
      work2Article1.innerText=`${num}`;
    }
    work2BtnSub.onclick = function () {
      num += "-" ; 
      work2Article1.innerText=`${num}`;
    }
   
    // 数字点击事件
    work2Btn1.onclick =function(){
      if( num == "0" ){
        num = "1";
      }else{
        num += "1" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn2.onclick =function(){
      if( num == "0" ){
        num = "2";
      }else{
        num += "2" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn3.onclick =function(){
      if( num == "0" ){
        num = "3";
      }else{
        num += "3" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn4.onclick =function(){
      if( num == "0" ){
        num = "4";
      }else{
        num += "4" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn5.onclick =function(){
      if( num == "0" ){
        num = "5";
      }else{
        num += "5" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn6.onclick =function(){
      if( num == "0" ){
        num = "6";
      }else{
        num += "6" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn7.onclick =function(){
      if( num == "0" ){
        num = "7";
      }else{
        num += "7" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn8.onclick =function(){
      if( num == "0" ){
        num = "8";
      }else{
        num += "8" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn9.onclick =function(){
      if( num == "0" ){
        num = "9";
      }else{
        num += "9" ;
      }
      work2Article1.innerText=`${num}`;
    }
    work2Btn0.onclick =function(){
      if( num == "0" ){
        num = "0";
      }else{
        num += "0" ;
      }
      work2Article1.innerText=`${num}`;
    }
  
  
    work2BtnEqu.onclick = function () {
      // num = Number(num);


      //检测运算符号的位置 
      function obtainSymbol(){
        var num1 = [];
        var o = 0 ;
        for(var i = 0 ; i<=num.length ; i++){
          if(num.charAt(i)=='+'){
            num1[o] = i ;
            o++;
          }else if(num.charAt(i)=='-'){
            num1[o] = i ;
            o++;
          }else if(num.charAt(i)=='*'){
            num1[o] = i ;
            o++;
          }else if(num.charAt(i)=='/'){
            num1[o] = i ;
            o++;
          }else if(num.charAt(i)=='%'){
            num1[o] = i ;
            o++;
          }
        }
        return num1 ;
      }

      var res1 = 0 ;     //计算结果
      var numStar = num ;  //重新获取原式子
      // 检测乘除取余运算
      var num1 = obtainSymbol();
      console.log(num1);

      // 检测除了第一个符号之外的乘除取余运算
      for( var w = 0 ; w <= num1.length ; w++ ){
        if(w != 0){
          if( num.charAt(num1[w]) == '*' || num.charAt(num1[w]) == '/' || num.charAt(num1[w]) == '%' ){
            if(w != num1.length-1){
              switch(num.charAt(num1[w])){
              case '*': var l =Number(num.substring(num1[w-1],num1[w]))*Number(num.substring(num1[w]+1,num1[w+1])) ;
                  console.log(l);
                  num = num.substring(0,num1[w-1]+1) + l + num.substring(num1[w+1]) ; 
                  break;
              case '/': var l =Number(num.substring(num1[w-1],num1[w]))*Number(num.substring(num1[w]+1,num1[w+1])) ;
                  num = num.substring(0,num1[w-1]+1) + l + num.substring(num1[w+1]) ; break;
              case '%': var l =Number(num.substring(num1[w-1],num1[w]))*Number(num.substring(num1[w]+1,num1[w+1])) ;
                  num = num.substring(0,num1[w-1]+1) + l + num.substring(num1[w+1]) ; break;
              }
            }else if(w == num1.length-1 ){
              switch(num.charAt(num1[w])){
              case '*': var l =Number(num.substring(num1[w-1]+1,num1[w])) * Number(num.substring(num1[w]+1)) ;
                  num = num.substring(0,num1[w-1]+1) + l ;
                  break;
              case '/': var l =Number(num.substring(num1[w-1]+1,num1[w])) / Number(num.substring(num1[w]+1)) ;
                  num = num.substring(0,num1[w-1]+1) + l ; break;
              case '%': var l =Number(num.substring(num1[w-1]+1,num1[w])) % Number(num.substring(num1[w]+1)) ;
                  num = num.substring(0,num1[w-1]+1) + l; break;
              }
            }
          num1 = 0 ;
          num1 = obtainSymbol();
          w -= 1;
          }
        }
      }
      
      // 从第一位运算符开始运算
      for(var k = 0 ; k < num1.length ; k++){
        if(k==0){        
          switch(num.charAt(num1[k])){
            case '+': res1 += Number(num.substring(0,num1[k])) + Number(num.substring(num1[k]+1,num1[k+1])) ; break;
            case '-': res1 += Number(num.substring(0,num1[k])) - Number(num.substring(num1[k]+1,num1[k+1])) ; break;
            case '*': res1 += Number(num.substring(0,num1[k])) * Number(num.substring(num1[k]+1,num1[k+1])) ; break;
            case '/': res1 += Number(num.substring(0,num1[k])) / Number(num.substring(num1[k]+1,num1[k+1])) ; break;
            case '%': res1 += Number(num.substring(0,num1[k])) % Number(num.substring(num1[k]+1,num1[k+1])) ; break; 
          }
        }else{
          switch(num.charAt(num1[k])){
            case '+': 
              if(k==num1.length-1){
              res1 += Number(num.substring(num1[k]+1)) ;
            
              }else{
                res1 += Number(num.substring(num1[k]+1,num1[k+1])); 
              }break;
            case '-': 
              if(k==num1.length-1){
              res1 -= Number(num.substring(num1[k]+1)) ;
              }else{
                res1 -= Number(num.substring(num1[k]+1,num1[k+1])); 
              }break;
            case '*': 
              if(k==num1.length-1){
              res1 *= Number(num.substring(num1[k]+1)) ;
              }else{
                res1 *= Number(num.substring(num1[k]+1,num1[k+1])); 
              }break;
            case '/': 
              if(k==num1.length-1){
              res1 /= Number(num.substring(num1[k]+1)) ;
              }else{
                res1 /= Number(num.substring(num1[k]+1,num1[k+1])); 
              }break;
            case '%': 
              if(k==num1.length-1){
              res1 %= Number(num.substring(num1[k]+1)) ;
              }else{
                res1 %= Number(num.substring(num1[k]+1,num1[k+1])); 
              }break;
          }
          
        } 
      }
  
      work2Article1.innerText=`${numStar}=${res1}`;
    }
  </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
js表格分页实现代码
Sep 18 Javascript
精通Javascript系列之数据类型 字符串
Jun 08 Javascript
js创建对象的区别示例介绍
Jul 24 Javascript
JavaScript设计模式经典之工厂模式
Feb 24 Javascript
深入理解js generator数据类型
Aug 16 Javascript
Vue学习笔记进阶篇之单元素过度
Jul 19 Javascript
JavaScript实现购物车基本功能
Jul 21 Javascript
关于单文件组件.vue的使用
Sep 20 Javascript
JavaScript数据结构之栈实例用法
Jan 18 Javascript
一文了解vue-router之hash模式和history模式
May 31 Javascript
如何测量vue应用运行时的性能
Jun 21 Javascript
JavaScript利用键盘码控制div移动
Mar 19 Javascript
jQuery实现颜色打字机的完整代码
Mar 19 #jQuery
webpack 动态批量加载文件的实现方法
Mar 19 #Javascript
vue-cli3项目升级到vue-cli4 的方法总结
Mar 19 #Javascript
js实现经典贪吃蛇小游戏
Mar 19 #Javascript
javascrpt密码强度校验函数详解
Mar 18 #Javascript
Node.js Domain 模块实例详解
Mar 18 #Javascript
js判断密码强度的方法
Mar 18 #Javascript
You might like
PHP return语句的另一个作用
2014/07/30 PHP
浅析PHP7的多进程及实例源码
2019/04/14 PHP
php中get_object_vars()在数组的实例用法
2021/02/22 PHP
JavaScript和ActionScript的交互实现代码
2010/08/01 Javascript
基于jquery点击自以外任意处,关闭自身的代码
2012/02/10 Javascript
将字符串转换成gb2312或者utf-8编码的参数(js版)
2013/04/10 Javascript
jquery实现图片裁剪思路及实现
2013/08/16 Javascript
当鼠标滑过文本框自动选中输入框内容的JS代码分享
2013/11/26 Javascript
IE浏览器不支持getElementsByClassName的解决方法
2014/08/27 Javascript
基于jquery实现智能提示控件intellSeach.js
2016/03/17 Javascript
JS实现把鼠标放到链接上出现滚动文字的方法
2016/04/06 Javascript
jquery实现垂直和水平菜单导航栏
2020/08/27 Javascript
js学习笔记之事件处理模型
2016/10/31 Javascript
JavaScript的事件机制详解
2017/01/17 Javascript
jQuery为某个div加入行样式
2017/06/09 jQuery
mint-ui在vue中的使用示例
2018/04/05 Javascript
手把手带你封装一个vue component第三方库
2019/02/14 Javascript
vue实现Input输入框模糊查询方法
2021/01/29 Javascript
js实现掷骰子小游戏
2019/10/24 Javascript
使用kbone解决Vue项目同时支持小程序问题
2019/11/08 Javascript
vue中实现弹出层动画效果的示例代码
2020/09/25 Javascript
跟老齐学Python之dict()的操作方法
2014/09/24 Python
Python使用pygame模块编写俄罗斯方块游戏的代码实例
2015/12/08 Python
python中文乱码不着急,先看懂字节和字符
2017/12/20 Python
对python中Librosa的mfcc步骤详解
2019/01/09 Python
python lambda表达式在sort函数中的使用详解
2019/08/28 Python
python中Ansible模块的Playbook的具体使用
2020/05/28 Python
html5 canvas-1.canvas介绍(hello canvas)
2013/01/07 HTML / CSS
爱尔兰灯和灯具网上商店:Lights.ie
2018/03/26 全球购物
三年级科学教学反思
2014/01/29 职场文书
感恩节活动策划方案
2014/05/16 职场文书
知识竞赛拉拉队口号
2014/06/16 职场文书
2014银行领导班子群众路线对照检查材料思想汇报
2014/09/17 职场文书
新手入门Jvm-- JVM对象创建与内存分配机制
2021/06/18 Java/Android
详解Java线程池是如何重复利用空闲线程的
2021/06/26 Java/Android
原型和原型链 prototype和proto的区别详情
2021/11/02 Javascript