繁体   English   中英

用于构建JavaScript计算器的切换方法

[英]Switch Method for building a javascript calculator

我正在尝试通过使用switch方法来构建计算器。 由于某种原因,我似乎无法弄清楚我的加法函数有效,但是我的减法函数却无法。 这可能是一个简单的解决方法,但我有点像新手。 任何见解将是伟大的! 谢谢。

 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; } 

使用您提供的内容,可能的原因是在函数的末尾而不是在需要switch语句之前定义了operationRequested

function handleOperationClick(operator)末尾的行

operationRequested = operator || operationRequested;

应该在线上方

switch(operationRequested){

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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