简体   繁体   中英

Switch Method for building a javascript calculator

I am trying to build a calculator by using a switch method for my operations. For some reason that i can't seem to figure out my addition function works, but my subtraction function won't. It may be a simple fix, but i am sorta a newbie. Any insight would be great!! thanks.

 var operatorPressed = false; var prevOperand = 0; var currentOperand = 0; var operationRequested = ''; // Creates calculator display input var displayNumbers = document.getElementById("display"); // Clears calculator display and var a values function clearMemory() { displayNumbers.value = ""; prevOperand = 0; //var a = 0; //console.log(a); }; function clearDisplay() { displayNumbers.value = ""; }; // Displays values on calculator screen var displayValue = function(num) { if (displayNumbers.value.length > 9) { displayNumbers.value = "ERROR"; } else { displayNumbers.value = num; //document.getElementById("display").value += Num; }; }; function handleNumberClick(num){ currentOperand = operatorPressed ? num : displayNumbers.value + num; operatorPressed = false; displayValue(currentOperand); } function clearNumberEntered(){ numberEntered=''; clearDisplay(); } //Operators // function function handleOperationClick(operator){ var result; operatorPressed = true; switch(operationRequested){ case 'add': result = add(prevOperand, currentOperand); break; case 'subtract': result = subtract(prevOperand, currentOperand); break; default: result = ''; } if(result){ //if an acutal computation occurs, we'll store overwrite the result to the prevOperand displayValue(result); prevOperand = result; } else { //if no computation occurs we'll just set the input val as the prevOperand prevOperand = currentOperand; } console.log("operation:%s %d to %d", operationRequested, currentOperand, prevOperand ); operationRequested = operator || operationRequested; } function add(num, adder){ var sum = parseInt(num) + parseInt(adder); return sum; } function subtract(num, subtracter) { var difference = parseInt(num) - parseInt(subtracter); return difference; } 

With what you have provided, the likely cause is operationRequested is being defined at the end of the function instead of before the switch statement where it is required.

The line at the end of the function handleOperationClick(operator)

operationRequested = operator || operationRequested;

should be above the line

switch(operationRequested){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM