JS implementation calculator details and instance code (1)

Source: Internet
Author: User
Tags function calculator
This article mainly introduces how to implement a calculator in JS and related information about the instance code. Here, I will explain the ideas and implementation steps for implementing the calculator. If you need it, you can refer to the following Javascript implementation calculator:

Series of articles:

JS implementation calculator details and instance code (1)

Detailed description and example of the time function of the calculator implemented by Javascript (2)

Small JavaScript Calculator

The clumsy method for self-developed solutions, although completed, has many bugs, and the method used is not the most effective. The basic functions are completed, some small details have also been taken into consideration, but there are other details to deal.

The overall design idea is to first sketch-> Design UI-> write UI code-> write CSS-> write JS logic code;

Panel (main-board)

Overall panel Size Design

Import new fonts

// Main.css @ font-face {font-family: Lovelo-Black;/X defines the font name ×/src: url ('font/Lovelo Black. otf');/* introduce the downloaded font file /}

Code Analysis

Code Organization Structure

Calculator object: Calculator;

Calculator attributes:

BdResult: The Screen Display DOM object on the calculator panel;

Operator: operator array, including '+,-, ×, operator, = ';

Digits: a valid number, including '0-9' and periods '.';

Dot, equal, zero: '.', '=', '0' must be three characters, point, equal sign, and character '0 ';

Digit: the current number displayed at the upper layer of the screen display area;

Expression: an expression composed of input numbers and operators displayed at the lower layer of the screen display area;

ResSpan: The span object that displays the current number at the upper layer of the screen display area;

ResDown: p object of the display expression at the lower layer of the screen display area;

Last: the content of the last input button;

AllDigits: all valid numbers in the expressions parsed by expressions;

Ops: all operators in the expressions parsed using expression strings;

HasEqual: determines whether the equal sign '=' is followed;

LastRes: The last calculated result [TODO], which is not used yet. It can be computed continuously;

Calculator method:

Init: calculator initialization method;

AddTdClick: Add a click event for each td, that is, the calculator button;

CalculatorClickEvent: Click an event;

BtnClickHanlder: Click the event processing function;

ShowCurrRes: process the content to be displayed at the upper and lower layers of the screen display area;

ShowText: displays the result processed by showCurrRes;

AddZero: Add '0' to the expression;

CalResult: calculation result;

ClearData: clear data;

HasOperator: determines whether an expression has an operator;

IsOperator: determines whether the current character is an operator;

DelHeadZero: delete '0' at the beginning of the expression ';

Auxiliary Methods

GetResSpan: Get the span object on the upper layer of the screen display;

$ Tag: obtains tag Objects Based on tag names;

$: Get the DOM object based on the id;

Code Logic

Usage

Introduce the Calculator. js file (on the basis of compiling the UI)

Create an object and initialize it: new Calculator (). init ();

Calculator object

// Calculator object function Calculator () {// Private Attribute this. bdResult = $ ("board-result"); // the display area object of the computer panel result. this. operator = ['+', '-', '×', 'hour', '=']; this. digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8 ', '9 ','. ']; // an array of valid numbers this. dot = '. '; this. equal = '; this. zero = '0'; this. digit = ""; // the number currently entered this. expression = ""; // expression this. resSpan = getResSpan (); // number display area this. resDown = $ ("result-down"); // expression display area this. last = ""; // the content of the button that was last pressed this. allDigits = []; // an array composed of all the numbers obtained from the expression, which is used to calculate the result corresponding to the operators in ops. this. ops = []; // an array composed of all operators this. hasEqual = false; // determines whether the '=' key is pressed. this. lastRes = 0; // the result of the last calculation, that is, the value calculated after the last equal sign // Private method}

Add click events (pay attention to the reference of this in the closure)

// Add a click event Calculator For td. prototype. addTdClick = function () {var tds = $ tag ("td"); var that = this; // save this reference. // Add a click event for each td (var I = 0; I <tds. length; I ++) {tds [I]. onclick = function () {// alert (this. innerText); var text = this. innerText; that. calculatorClickEvent (text );};}};

Calculator click event processing entry

// Calculator button event. prototype. calculatorClickEvent = function (btnText) {// The previous key is '=' if (this. hasEqual) {this. hasEqual = false; this. clearData ();} // The result is displayed in the board-result if (btnText! = "AC" & btnText! = "CE") {this. btnClickHanlder (btnText);} else {// AC or CE: this. clearData ();}};

Calculator Click Event Handler

// Calculator is used to process key events of the Calculator. prototype. btnClickHanlder = function (btnText) {if (btnText> = '0' & btnText <= '9') | btnText = this. dot) {// number key processing // if the previous operator is used, clear the current number zone if (this. isOperator (this. last) {this. resSpan. innerText = ''; this. digit = '';} else if (btnText = this. dot) & (this. last = this. dot) {// if the previous vertex is also a vertex, return is not returned for this vertex button;} this. digit + = btnText; this. expression + = btnText;} e Lse if (this. isOperator (btnText) {// operator processing // if the current expression is '0', press '=' and no response if (btnText = this. equal) & (this. resDown. innerText = this. zero | this. resDown. innerText = "") return; // if the previous operator is not '=', it will not be processed if (! This. isOperator (this. last) & btnText = this. equal) {// '=' process this. showCurrRes (this. zero, this. expression + btnText); // The calculation result is displayed in return;} else if (this. isOperator (this. last) {// The previous operator does not record return;} else {this. expression + = btnText;} this. showCurrRes (this. digit, this. expression); this. last = btnText ;};

Process the expression to be displayed and the number currently entered

// Trigger method Calculator. prototype. showCurrRes = function (digit, expression) {if (! Expression) return; this. showText (digit, expression); // 1. if (expression. indexOf (this. equal) =-1) return; // The result is calculated. this. hasEqual = true; // 2. if you only press a number and then directly press the equal sign, that is, '2014 = ', 234 var tmpStr = this is returned directly. delHeadZero (expression. substr (0, expression. length-1); // remove the last '=' if (! This. hasOperator (tmpStr) {this. showText (tmpStr, expression + tmpStr); return;} // 3. process the expression string and calculate the result var start = 0; for (var I = 0; I <expression. length; I ++) {var c = expression [I]; if (this. isOperator (c) {// operator this. ops. push (c); // save operator var numStr = expression. substr (start, I + 1); // numeric string var number = 0; // if (numStr. indexOf (this. dot) {number = parseFloat (numStr);} else {number = parseInt (numStr);} this. allDigits. push (number); // Save the number start = I + 1; // reset the start position of the number, that is, start with the next character of the operator} // use allDigits and ops to calculate the result var res = this. calResult (); // Save the calculation result and use [TODO] this as the next calculation. lastRes = res; // display the result this. showText (res + '', expression + res );};

Display the processing result to the screen display area

// Display the expression and calculation result to the Calculator in the screen display area. prototype. showText = function (digitStr, expression) {// first Delete the '0' var expStr = this. delHeadZero (expression); var digStr = this. delHeadZero (digitStr); // determine whether to add '0' var tmp = expression = this. zero? Expression: this. addZero (expStr); var dig = digitStr = this. zero? DigitStr: this. addZero (digStr); this. resSpan. innerText = dig; // if the first expression is an operator, it indicates that the previous expression is '0', then add '0' to it ', because if (this. isOperator (tmp [0]) {tmp = this. zero + tmp;} this. resDown. innerText = tmp ;}

Calculation Result Function

// Calculate the result Calculator. prototype. calResult = function () {var first = 0; var second = 0; var res = 0; for (var I = 0; I <this. ops. length; I ++) {first = this. allDigits [I]; second = this. allDigits [I + 1]; switch (this. ops [I]) {case '+': res = first + second; break; case '-': res = first-second; break; case '× ': res = first * second; break; case 'hour': res = first/second; break; default: break;} this. allDigits [I + 1] = res;} return res ;};

Clear Data

// After calculation, all data is cleared for the next calculation. prototype. clearData = function () {this. allDigits = []; this. ops = []; this. expression = this. zero; this. digit = ''; this. resSpan. innerText = this. zero; this. resDown. innerText = this. zero ;};

Auxiliary Functions

Handle the '0' problem at the beginning of the expression (the first button is the 0 key or the first is a floating point number smaller than 1, the expression needs to be filled with zero ;)

// Add '0' at the beginning to prevent repeated occurrences or absence of '0'. Calculator. prototype. addZero = function (expression) {if (! Expression) return this. zero; if (expression [0] = this. dot) {// floating point return this. zero + expression;} else {return expression ;}};

0-Core Function

// Start with 0 Calculator. prototype. delHeadZero = function (str) {// Delete All '0' starting with var tmp = ""; tmp = str. replace (/^ [0] +/gi, ""); if (tmp [0] = this. dot) {// Add '0' tmp = this to the floating point number. zero + tmp;} return tmp ;};

Determines whether the string contains operators.

// Determine whether the expression contains the operator Calculator. prototype. hasOperator = function (str) {if (! Str) return; for (var I = 0; I <this. operator. length; I ++) {if (str. indexOf (this. operator [I]) >=0) {return true ;}} return false ;};

Other functions

// Obtain the input number display area object function getResSpan () {return $ ("result-up "). getElementsByTagName ("span") [0];} // obtain the DOM object function $ tag (tagName) {return document. getElementsByTagName (tagName);} // obtain the DOM object function $ (ID) {return document. getElementById (id );}

Problem

Display at the bottom of the text: Set the line height;

To use a one-time parsing expression, consider whether '0' must exist at the beginning of the expression;

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

For more details about JS implementation calculators and instance code (1) related articles, please pay attention to PHP!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.