簡體   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