search
HomeWeb Front-endJS TutorialDetailed explanation of JS implementation of web calculator based on recursive algorithm

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.

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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft