javascript implements a numerical addition function

  • 2020-06-22 23:50:19
  • OfStack

Without further ado, I'll just hand over the code

JS


<script type="text/javascript">
function Sum(arg1,arg2){ // Numerical addition function 
var sarg1 = new String(arg1); // Converts the passed argument to a string for parameter checking 
var sarg2 = new String(arg2); // The parameter 2 Convert to character type 
if( (sarg1=="")||(sarg2=="") ) // Make sure the parameter is not null 
{
var e0 = new Error(); // An exception is thrown when an argument is null 
e0.Serial = 1000001; // Wrong number 
if( sarg1=="" ) // Correctly fill in the error message based on the empty parameter 
{
e0.message = "Sum Invalid function parameter: no 1 The parameters are empty! "; // Error description information 
}
else
{
e0.message = "Sum Invalid function parameter: no 2 The parameters are empty! ";
}
throw e0; // Throw an error message 
}
for(i=0;i<sarg1.length;i++){ // Parameter validity check 
for(j=0;j<10;j++){ // Check all characters 
if(sarg1.charAt(i)==j) // If it is not a number, an error message is thrown 
{
break; // Jump out of the loop 
}
else
{
if(j==9) // When the number has been queried 9 when 
{
var e1 = new Error(); // Error message object 
e1.Serial = 1000001; // Wrong number 
e1.message = "Sum Function parameters: " + sarg1 + " Illegal number! "; // Error description information 
throw e1;
}
}
}
}
for( k=0;k<sarg2.length;k++ ) // Check the parameters 2 The digital 
{
for(l=0;l<10;l++){ // from 0 to 9 One by one 1 To compare 
if(sarg2.charAt(k)==l) // If it is 0~9 The number of 
{
break;
}
else
{
if(l==9) // An error message is thrown if only it contains a non-number 
{
var e2 = new Error(); // Creating the error object 
e2.Serial = 1000001; // Abnormal number 
e2.message = "Sum Function parameters: " + sarg2 + " Illegal number! ";
throw e2;
}
}
}
}
return Number(arg1) + Number(arg2); // Returns the sum of two values if both parameters are correct 
} 
function Button1_onclick(){ // Compute the stand-alone event handler for the button 
try{
var Text1 = document.getElementById("Text1");
var Text2 = document.getElementById("Text2");
var Text3 = document.getElementById("Text3");
var sum = Sum(Text1.value,Text2.value); // Call the function to do the calculation 

Text3.value = sum; // Output calculation result 
}
catch(e){ // Output error message when error occurs 
alert(e.message); // Output the information in the exception 
if(e.Serail == 1000001) // If it is 1000001 Error no. 
{
alert(e.message); 
e = null;
}
}
}
</script>

HTML:


<input type="text" id="Text1" style="width:84px" maxlength="20"/>
+
<input type="text" id="Text2" style="width:75px" maxlength="20"/>
=
<input type="text" id="Text3" style="width:69px">
<input type="button" id="Button1" value=" To calculate " onclick="return Button1_onclick()" />

This is the end of this article, I hope you enjoy it.


Related articles: