Example Analysis of arguments usage in Javascript and arguments instance analysis
This example describes how to use arguments in Javascript. Share it with you for your reference. The specific analysis is as follows:
Let's take a look at the following example:
Function add (n1, n2) {return n1 + n2;} function add (n1, n2, n3) {return n1 + n2 + n3;} alert (add (1, 2 )); // NaN, the method called in js adopts the proximity principle; // The result is NaN because the method is not passed in n3.
Js does not support method overloading. How can this problem be solved?
// Arguments function f1 () {var sum = 0; for (var I = 0; I <arguments. length; I ++) {sum + = arguments [I];} return sum;} alert (f1 (1, 2, 3, 4, 5); // use arguments, in the calculation example, add the number and function ff (name) {var sum = 0; for (var I = 1; I <arguments. length; I ++) {sum + = arguments [I];} return arguments [0] + sum;} alert (ff ('example ', 1, 2, 3, 4, 5); // example 15 // name, age function test (name, age) {if (! Age) {// age when no parameter is passed, age is undefined age = 18;} alert ('name is '+ name +' age is '+ age );} test ('James '); // The name is James. The age is 18.
I hope this article will help you design javascript programs.