Home  >  Article  >  Web Front-end  >  How to implement a web version of calculator in JS

How to implement a web version of calculator in JS

亚连
亚连Original
2018-06-19 15:55:563398browse

This article mainly introduces the method of JS based on recursion to implement the web version of the calculator. It analyzes the steps and related operating techniques of using the recursive algorithm in JavaScript to implement the web version of the calculator in the form of examples. Friends in need can refer to the following

The example in this article describes the method of implementing the web version of the calculator based on JS recursion. Share it with everyone for your reference. The details are as follows:

Recursively implementing the web version of the calculator can simplify the code. Design ideas:

1. CSS+html implements the appearance of the calculator, giving each The button is bound to the number(z) event, and the difference in z is passed in to distinguish the button that triggered the event.

c9ccee2e6ea535a969eb3f532ad9fe89Put it in the head

This p is placed in the body, which is the HTML of the calculator. Number() distinguishes the trigger buttons by passing in different numbers.

<p class="bg">
 <p id="txt"></p>
 <button id="bt10" value="+">+</button>
 <button id="bt11" value="-">-</button>
 <button id="bt12" value="*">*</button>
 <br data-filtered="filtered"><button id="bt13" value="/">/</button>
 <button id="bt14" value="=">=</button>
 <br data-filtered="filtered"><button id="bt1" value="1">1</button>
 <button id="bt2" value="2">2</button>
 <button id="bt3" value="3">3</button>
 <br data-filtered="filtered"><button id="bt4" value="4">4</button>
 <button id="bt5" value="5">5</button>
 <button id="bt6" value="6">6</button>
 <br data-filtered="filtered"><button id="bt7" value="7">7</button>
 <button id="bt8" value="8">8</button>
 <button id="bt9" value="9">9</button> 
</p>

2. In the number(z) method, the innerHTML of the DOM is used to realize the real-time display of the expression, and the string content is used to store the clicked number or symbol. When "=" is clicked, Call fact(content) to calculate.

The code is as follows:

var content; //存储已点击的数字或符号,要定义成全局的,如果定义在number()中,每次content都会被重新赋值
function number(z) {
  var k=document.getElementById("txt");//获取显示框的 DOM,并缓存在k中
  if(z==14){//如果点击了"="号
   var sum = fact(content);//调用fact()进行计算,并把结果赋值给sum
   content=content+"="+sum;//在要显示的内容后加入"="和sum
   k.innerHTML = content;
   content = null;//将content清空,准备下次计算
  }else{
  //如果没有点击"="号,而是点击的运算符,就需要通过switch把数字转化成运算符
   switch(z){
    case 10: z = &#39;+&#39;; break;
    case 11: z = &#39;-&#39;; break;
    case 12: z = &#39;*&#39;; break;
    case 13: z = &#39;/&#39;; break;
   }
   //把此时输入的字符存入content
   if(content){
    content+=z.toString();
   }else{
    content=z.toString();
   }
   k.innerHTML = content;//让它实时显示
  }
}

3. The idea of ​​the recursive algorithm in this calculator: In fact(content), first Use content.indexOf(" ") to determine whether the " " number exists. If it exists, recursively call the two strings before and after index and add them until no strings are found. " ", start using content.lastIndexOf("-") to judge the "-" sign. The subsequent operation is the same as the plus sign. If there is one, recurse the two strings before and after the index and subtract them. Until the minus sign is not found, it starts to judge the multiplication sign and division sign, and returns parseFloat(content) until there is no sign. The content here is the unsigned string after the recursive call, and is not introduced at the beginning. parameters.

//实现递归计算
function fact(content){
 var index = content.indexOf("+");//获取"+"号的index
 if(index != -1){
  return fact(content.substring(0,index))+fact(content.substring(index+1));
  //当找得到“+”号时,分成两部分相加递归
 }else{
  var index2 = content.lastIndexOf("-");//当找不到“+”号时,开始找“-”号
  if(index2 != -1){
   return fact(content.substring(0,index2))-fact(content.substring(index2+1));
   //当找得到“-”号时,分成两部分相减递归
  }else{
   var index3 = content.indexOf("*");//当找不到“-”号时,开始找“*”号
   if(index3 != -1){
    return fact(content.substring(0,index3))*fact(content.substring(index3+1));
    //当找得到“*”号时,分成两部分相乘递归
   }else{
    var index4 = content.lastIndexOf("/");//当找不到“*”号时,开始找“/”号
    if(index4 != -1){
     return fact(content.substring(0,index4))/fact(content.substring(index4+1));
     //当找得到“/”号时,分成两部分相除递归
    }else{
     return parseFloat(content);//当找不到“/”号时,返回这段串的变成float型的数值
    }
   }
  }
 }
}

The above is all the code. Two points to pay attention to in the design idea are:

1. The plus sign and multiplication sign are indexOf(), and the minus sign is Use lastIndexOf() with the division sign.

For example: content="3-2-1"

If it uses indexOf(), first divide the string into fact("3" )-fact("2-1"), the first "3" is unsigned, and when calling fact recursively, it returns parseFloat("3"), and when it is followed recursively, it will become parseFloat("2")-parseFloat("1")=1, this is the return value of fact("2-1"), the final result is 2, which is equivalent to :3-(2-1).

If lastIndexOf() is used, it divides the string into fact("3-2")-fact("1"), fact("3-2")# The return value of ## is parseFloat("3")-parseFloat("2")=1, thus realizing calculation from left to right.

The division sign is the same: if content="6/3/2" uses indexOf(), it is equivalent to: 6/(3/2), because there is no order problem with the plus sign and the multiplication sign, so You can use indexOf().

2. Multiplication and division are in the inner layer of judgment, and addition and subtraction are in the outer layer of judgment.

Since multiplication and division must be calculated first, the inner judgment will first obtain the unsigned string, and they will calculate it first.

What I personally think can be optimized about this calculator: (You can also think about it)

1. When binding events to buttons, use the event proxy mode.

2. Which properties or methods are used need to consider browser compatibility issues.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use vuex to implement menu management

How to use Vue to develop tree components

Detailed interpretation of the new features of Angular5.1

How to implement gulp packaging using nodejs

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

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