Home  >  Article  >  Web Front-end  >  Detailed explanation of JS implementation of web calculator based on recursive algorithm

Detailed explanation of JS implementation of web calculator based on recursive algorithm

小云云
小云云Original
2017-12-21 14:29:461587browse

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 JavaScript using the recursive algorithm to implement the web version of the calculator in the form of examples. Friends who need it can refer to it. I hope it can help. Everyone.

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

1. CSS+html implements the appearance of the calculator, binds the number(z) event to each button, and passes The difference in input z distinguishes the button that triggers 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, use the innerHTML of the DOM to realize the real-time display of the expression, and use the string content to store the clicked number or symbol, when "=" is clicked, fact(content) is called for calculation.

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: Infact (content), first use content.indexOf("+") to determine whether the "+" sign exists. If it exists, recursively call the two strings before and after index, and let them Add up until "+" is not found in all strings, then use content.lastIndexOf("-") to judge the "-" sign. The subsequent operation is the same as the plus sign. If it exists, recurse before and after the index. Two strings, and subtract them until no minus sign is found, then start to judge the multiplication sign and division sign, until there is no sign, return parseFloat(content), the content here is a recursive call The unsigned string after is not the first parameter introduced.


//实现递归计算
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 indexOf used for the plus sign and multiplication sign (), while the minus sign and division sign use lastIndexOf().

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.

I first made a non-recursive calculator for addition, subtraction, multiplication and division of two numbers. When I improved it later, I wanted to calculate multiple numbers, which became more complicated to think about. When written recursively, the code size is smaller than before, easy to read, and not complicated to think about. Those who are interested can give it a try.

Related recommendations:


implementation of simple four arithmetic operations calculator function in PHP

Example of php function to realize advanced calculator (Based on stack)

Use jQuery to implement a simple calculator

The above is the detailed content of Detailed explanation of JS implementation of web calculator based on recursive algorithm. 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