The arguments object verifies that the arguments to the function are valid

  • 2020-06-19 09:47:55
  • OfStack

Use the arguments object to verify that the arguments to the function are valid


<script>
function sum(arg1,arg2) // Add function 
{
var realArgCount = arguments.length; // The number of arguments passed when a function is called 
var frmArgCount = sum.length; // The number of formal parameters at which a function is defined 
if(realArgCount < frmArgCount) // If the number of actual parameters is less than the number of formal parameters 
{
var e = new Error(); // Define an error message and throw it 
e.number = 1000001; // Wrong number 
e.message = " The actual number of parameters does not meet the requirements! " // The error message 
throw e;
}
return arguments[0] + arguments[1];// If the parameters meet the requirements, from arguments Object and returns the sum of the two 
}
try
{
document.write("<p><h1>arguments Object to test </h1></p>"); // Output the title 
document.write(" The result of the correct call: "+sum(10,20));// Output the result of the correct call 
document.write("<br> Results of calls that do not conform to the rules: "); // man-made 1 Not conforming to the rules of the call 
document.write(sum(10));
}
catch(e) // Capture error messages 
{
alert(e.number+" Error no. : "+e.message);
}
</script>

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


Related articles: