基于if/else语句的JavaScript简易计算器开发技术求助
Fixing Your Basic JavaScript Calculator with if/else Statements
Hey there! Let's work through fixing your calculator step by step—since you're a new programmer, I'll break down each part clearly and stick strictly to using if/else as your project requires.
First: Fixing the Loop & Button Click Handlers
Your existing loop has a few syntax and logic issues. Let's correct those first:
- Grab the right elements: Since your calculator lives inside a form named
calc, we can usedocument.forms.calc.elementsto get all input elements inside that form—this is more precise than selecting all inputs on the page. - Fix the for loop syntax: Your loop had a comma instead of a semicolon, and used
<=instead of<(we want to stop before reaching the length of the array). - Correctly check for button elements: We need to use strict equality (
===) and quote'button'since it's a string. Also,elsedoesn't take a condition—we just use it to skip non-button elements. - Pass the button ID correctly: To send the button's ID to your
calcufunction, wrap the call in an anonymous function sothisrefers to the clicked button.
Corrected Loop Code
// Get all input elements inside the calculator form var inputs = document.forms.calc.elements; // Loop through each input element for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; // Check if the element is a button if (input.type === 'button') { // Bind click event: pass the button's ID to calcu input.onclick = function() { calcu(this.id); }; } else { // Skip non-button elements (like the output textbox) continue; } }
Second:完善 the calcu() Function with if/else
Now let's build out the calcu function to handle each type of button using if/else statements. We'll cover:
- Number buttons (0-9)
- Operator buttons (+, -, *, /)
- Clear button (C)
- Equals button (=)
###完善ed calcu Function
var calcu = function(calcValue) { // Get the output textbox element var output = document.forms.calc.output; if (calcValue >= '0' && calcValue <= '9') { // Handle number buttons: append the digit to the output output.value += calcValue; } else if (calcValue === '+' || calcValue === '-' || calcValue === '*' || calcValue === '/') { // Handle operator buttons: add the operator with spaces for readability output.value += ' ' + calcValue + ' '; } else if (calcValue === 'c') { // Handle clear button: empty the output output.value = ''; } else if (calcValue === 'equate') { // Handle equals button: calculate the expression try { // Use eval for simplicity (note: eval is not recommended for production code, but works for school projects) var result = eval(output.value); output.value = result; } catch (error) { // Show error if the expression is invalid output.value = 'Error'; } } };
Full Working Code
Put it all together, and make sure to wrap everything in a DOMContentLoaded listener to ensure the HTML loads before we run the JavaScript:
// Wait for the page to fully load before running code document.addEventListener('DOMContentLoaded', function() { var calcu = function(calcValue) { var output = document.forms.calc.output; if (calcValue >= '0' && calcValue <= '9') { output.value += calcValue; } else if (calcValue === '+' || calcValue === '-' || calcValue === '*' || calcValue === '/') { output.value += ' ' + calcValue + ' '; } else if (calcValue === 'c') { output.value = ''; } else if (calcValue === 'equate') { try { var result = eval(output.value); output.value = result; } catch (error) { output.value = 'Error'; } } }; var inputs = document.forms.calc.elements; for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; if (input.type === 'button') { input.onclick = function() { calcu(this.id); }; } else { continue; } } });
Key Notes
- Using
document.forms.calcmakes it easy to access the calculator form and its elements without extragetElementByIdcalls. - The anonymous function in the click handler ensures
thisrefers to the button that was clicked, so we can pass its ID correctly. - Adding spaces around operators helps
evalparse the expression correctly (and makes it easier for users to read). - The
try/catchblock handles invalid expressions (like1++2) so the calculator doesn't break.
内容的提问来源于stack exchange,提问作者Elisabeth
相关产品推荐
相关产品推荐

