background
Because I was assigned to a new project team, the project needs js. Because I haven't contacted it, the leader is going to give me a week to study. Yes, realizing a simple calculator that supports four mixed operations is an assignment, so I have this article
Therefore, the main focus of this article is not html and css. After all, I only know a little about it and haven't studied it deeply
Realization effect
The final displayed page is shown in the figure below. When the mouse clicks the button, the button will change color, and four mixed operations can be carried out
The upper line displays the calculation formula. When "=" is pressed, the calculation result is displayed
Technology used
The calculator page is drawn using an html table
Key size, color, mouse hover color change are set with css
Click the button to display the value and calculation result on the button in the top line, and complete the four mixed operations. It is done with js
Realization idea
Here I have three files, one html a css one js
- First, I wrote html and css and drew the appearance of the web page. I won't elaborate here. If you are interested, you can look at the code directly
- Then use js DOM events to add click events to different types of buttons and call different JS functions.
At the beginning of this step, I just wrote a function definition, mainly to divide the logic first, such as what functions should be realized and what effects should be displayed by pressing a key, and then fill in the function logic so that the logic will not be disordered - Finally, implement js function, that is, complete four mixed operations. Focus on how to realize four mixed operations and display the results
-
When displaying the formula and results above, I defined an array of global variables. Each time I click the key, I will push the value of the key to the array. In this way, I will directly throw the array away when displaying. Another reason for this is that when you click the backspace key, you pop it. When you click the empty key, you directly assign an empty array to the array variable. It will be easier to operate
-
Next, a very important step is to calculate the expression. For example, how to evaluate an expression such as 3 * 4.5 - 1 =. The method I think of is to first turn the input array into an infix expression, then turn the infix expression into a suffix expression, and then evaluate the infix expression
1. Firstly, such an array is obtained through the above array processing['3','*','4','.','5','-','1'] 2. Convert this array into a string and change it to "3"*4.5-1" 3. It is then processed into a new array of operators and numbers ['3','*','4.5','-','1'] 4. After processing, the infix expression is changed into a suffix expression by using the stack 5. Then use the stack to evaluate the suffix expression, and fill in the result=after
Since step 4.5 is the content of stack application in data structure, if you are not clear, you can review the data structure and complete it now
Specific implementation code
As mentioned above, we have analyzed enough, so we won't say much about this and go directly to the code
. html file
<!DOCTYPE html> <html> <head> <title>calculator</title> <link rel="stylesheet" href="calculator.css"> <script src="calculator.js"></script> </head> <body> <div> <table border="1"> <thead> <th colspan="4"> <input type="text" id="result" disabled> </th> </thead> <tbody> <tr> <td><button class="operate" onclick="showNumber(this)">(</button></td> <td><button class="operate" onclick="showNumber(this)">)</button></td> <td><button class="operate" onclick="clearOneResult()">←</button></td> <td><button class="operate" onclick="clearResult()">C</button></td> </tr> <tr> <td><button class="calculate" onclick="showNumber(this)">7</button></td> <td><button class="calculate" onclick="showNumber(this)">8</button></td> <td><button class="calculate" onclick="showNumber(this)">9</button></td> <td><button class="operate" onclick="showNumber(this)">*</button></td> </tr> <tr> <td><button class="calculate" onclick="showNumber(this)">4</button></td> <td><button class="calculate" onclick="showNumber(this)">5</button></td> <td><button class="calculate" onclick="showNumber(this)">6</button></td> <td><button class="operate" onclick="showNumber(this)">-</button></td> </tr> <tr> <td><button class="calculate" onclick="showNumber(this)">1</button></td> <td><button class="calculate" onclick="showNumber(this)">2</button></td> <td><button class="calculate" onclick="showNumber(this)">3</button></td> <td><button class="operate" onclick="showNumber(this)">+</button></td> </tr> <tr> <td><button class="calculate" onclick="showNumber(this)">0</button></td> <td><button class="calculate" onclick="showNumber(this)">.</button></td> <td><button class="operate" onclick="showNumber(this)">/</button></td> <td><button class="operate" onclick="showAnswer()">=</button></td> </tr> </tbody> </table> </div> </body> </html>
. css file
table{ margin: 20px; padding: 1px; } th,input{ height: 120px; width: 410px; background-color:rgb(233, 232, 232); text-align: right; font-size: 40px; } button{ height: 100px; width: 100px; padding: 0px; font-size: 30px; } th,input,td,button{ border: 0px; } .calculate{ background-color: rgb(231, 231, 235); } .operate{ color: coral; } button:hover{ background-color: rgb(147, 241, 253); }
. js file
var result = new Array(); var ops = "+-*/"; function arrToStr(arr) { var strResult = ""; for (var i = 0; i < arr.length; i++) { strResult += arr[i]; } return strResult; } function showResult() { document.getElementById("result").value = arrToStr(result); } function showNumber(id) { var val = id.innerHTML; result.push(val); showResult(); } function showAnswer() { var answer = ""; var str = arrToStr(result); var midExpre = strToExpress(str); var suffixExpre = midToSuffix(midExpre); answer = suffixValue(suffixExpre); //console.log(midExpre); //console.log(suffixExpre); document.getElementById("result").value = str + "=" + answer; } function clearResult() { result = []; showResult(); } function clearOneResult() { result.pop(); showResult(); } function strToExpress(str) { var textArr = str.split(''); var newTextArr = []; var calTextArr = []; for (var i = 0; i < str.length; i++) { if (ops.indexOf(str[i]) != -1 ) { newTextArr.push("|", str[i], "|"); } else if (str[i] == '('){ newTextArr.push(str[i], "|"); } else if (str[i] == ')'){ newTextArr.push("|", str[i]); } else { newTextArr.push(textArr[i]); } } calTextArr = newTextArr.join('').split('|'); return calTextArr; } function midToSuffix(midExpre) { var opStack = []; var suffixExpre = []; for (var i = 0; i < midExpre.length; i++) { if (ops.indexOf(midExpre[i]) != -1 || midExpre[i] == '(' || midExpre[i] == ')' ) { if (midExpre[i] == '(' || opStack[opStack.length - 1] == '(') { opStack.push(midExpre[i]); } else if (midExpre[i] == ')') { do { suffixExpre.push(opStack.pop()); } while (opStack[opStack.length - 1] != '('); opStack.pop(); } else if (opStack.length == 0 || Priority(midExpre[i]) > Priority(opStack[opStack.length - 1])) { opStack.push(midExpre[i]); } else { do { suffixExpre.push(opStack.pop()); } while (opStack.length > 0 && Priority(midExpre[i]) <= Priority(opStack[opStack.length - 1])); opStack.push(midExpre[i]); } } else { suffixExpre.push(midExpre[i]); } } while (opStack.length > 0) { suffixExpre.push(opStack.pop()); } return suffixExpre; } function Priority(op) { var opPri = 0; switch (op) { case "+": opPri = 1; break; case "-": opPri = 1; break; case "*": opPri = 2; break; case "/": opPri = 2; break; } return opPri; } function suffixValue(suffixExpre) { var calStack = []; console.log(suffixExpre); for (var i = 0; i < suffixExpre.length; i++) { if (ops.indexOf(suffixExpre[i]) != -1) { var opRight = Number(calStack.pop()); var opLeft = Number(calStack.pop()); var tmpResult = 0; switch (suffixExpre[i]) { case '+': tmpResult = opLeft + opRight; break; case '-': tmpResult = opLeft - opRight; break; case '*': tmpResult = opLeft * opRight; break; case '/': tmpResult = opLeft / opRight; break; } calStack.push(tmpResult); } else { calStack.push(suffixExpre[i]); } console.log(calStack); } return calStack.pop(); }