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

时间:2016-01-09 21:57:04

标签: javascript switch-statement calculator

我正在尝试使用切换方法为我的操作构建计算器。由于某些原因,我似乎无法弄清楚我的加法函数是否有效,但我的减法函数不会出现。这可能是一个简单的修复,但我是一个新手。任何见解都会很棒!!感谢。



  

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




1 个答案:

答案 0 :(得分:0)

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

function handleOperationClick(operator)

末尾的行
operationRequested = operator || operationRequested;

应该在

之上
switch(operationRequested){