Knowledge points: 1. Use of mathematical operations ", -, *, /"
2. Judgment of input content, judgment of the source of event objects
Effect : Code:
Detailed breakdown:
First: The branch calculation part does not use switch statements, but uses the form of name-value pairs.
//Calculation object
var operateExp={
' ':function(num1,num2){return num1 num2;},
'-':function(num1,num2){return num1-num2;},
'*':function(num1, num2){return num1*num2;},
'/':function(num1,num2){return num2===0?0:num1/num2;}
}
Second: Use the properties of the object event to obtain the type of the clicked object. Use event bubbling to capture events and classify them.
calculate_num.onclick=function(e){
var ev = e || window.event;
var target = ev.target || ev.srcElement;
if(target.type=="button"){
var mark=target.getAttribute( "_type"); //Get the custom attributes of the currently clicked button.
var value=target.value;//Get the current value
var num=getScreen();//Get the value of the current box
if(mark==='bs'){//Exit Square key
if(num==0)return;
var snum=Math.abs(num).toString();
if(snum.length<2)
setScreen(0);
else
setScreen(num.toString().slice(0,-1));
}
if(mark==='num'){//numeric key
if (num==='0'||isReset){//There is an operator or the display is 0
setScreen(value);
isReset=false;
return;
}
setScreen(num.toString().concat(value));
}
if(mark==="."){//Decimal point
var hasPoint=num.toString().indexOf(" .")>-1;
if(hasPoint){
if(isReset){
setScreen("0" value);
isReset=false;
return;
}
return;
}
setScreen(num.toString().concat(value));
}
if(mark===" /-"){//Positive and negative No.
setScreen(-num);
}
if(mark==="op"){//If the click is an operator, design the first operand
if(isReset) return;
isReset=true;
if(!operation){
result= num;
operation=value;
return;
}
result=operateNum(result, num,operation);
setScreen(result);
operation=value;
}
if(mark==="cls"){//Clear
result=0;
setScreen(result);
isReset=false;
}
if(mark==="eval"){//Calculate
if(!operation)return;
result= operateNum(result,num,operation);
setScreen(result);
operation=null;
isReset=false;
}
}
}
Third: Use of global variables, use global variables to control the progress of local operations. (State control)
var result=0;//Calculation Result
var isReset=false;//Whether to reset
var operation;//Operator
Fourth: Separate and decouple page operations .
//Set the value of the display screen
function setScreen(num){
calculate_outPut.value=num;
}
//Get the value of the display screen
function getScreen (){
return calculate_outPut.value;
}
Fifth: Filter the operands and complete the calculation.
//Calculate function
var operateNum=function( num1,num2,op){
if(!(num1&&num2))return;
//Guarantee that num1 and num2 are both numbers
num1=Number(num1);
num2=Number(num2) ;
//No operator exists, return num1;
if(!op)return num1;
//Matching operation formula
if(!operateExp[op])return 0;
return operateExp[op](num1,num2);
}