[英]Switch Method for building a javascript calculator
I am trying to build a calculator by using a switch method for my operations. 我正在尝试通过使用switch方法来构建计算器。 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. 使用您提供的内容,可能的原因是在函数的末尾而不是在需要switch
语句之前定义了operationRequested
。
The line at the end of the function handleOperationClick(operator)
function handleOperationClick(operator)
末尾的行
operationRequested = operator || operationRequested;
should be above the line 应该在线上方
switch(operationRequested){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.