Common function definition methods:
function abs (x): { if (x >= 0) { return x; } else { return-x; }} The two methods are equivalent var abs = function (x): { if (x >= 0) { return x; } else { return-x; };
Arguments
JavaScript also has a free keyword arguments
that works only inside the function and always points to all parameters passed in by the caller of the current function. arguments
similar Array
but it is not a Array
:
function foo (x) { alert (x);//For (var i=0; i<arguments.length; i++) { alert (arguments[i]);//10, 2 0, }}foo (10, 20, 30);
With arguments, you can get all the arguments passed in by the caller. That is, even if the function does not define any parameters, it can get the value of the parameter: function abs () { if (arguments.length = = = 0) { return 0; } var x = arguments[0]; return x >= 0? ×:-X;} ABS (); 0abs (10); 10abs (-9); 9
function foo (A, B, c) { if (arguments.length = = = 2) { //The actual parameters obtained are a and b,c for undefined C = b;//assigning B to c b = null; B changed to default } //...}
Rest parameters because JavaScript functions allow the receipt of arbitrary parameters, we have to use arguments to get all parameters: function foo (A, b) { var i, rest = []; if (Arguments.length > 2) {for (i = 2; i<arguments.length; i++) { rest.push (arguments[i]); } } Console.log (' a = ' + a); Console.log (' B = ' + b); Console.log (rest);}
In order to get the parameters beyond the defined parameters A, B, we have to use arguments, and the loop to start at index 2 to exclude the first two parameters, this is very awkward, just to get extra rest parameters, there is no better way? The ES6 standard introduces the rest parameter, which can be rewritten as: function foo (a, B, ... rest) { Console.log (' a = ' + a); Console.log (' B = ' + b); Console.log (rest);} Foo (1, 2, 3, 4, 5);//Result://a = 1//b = 2//Array [3, 4, 5]foo (1);//Result:/a = 1//B = undefined//Array []rest parameter can only be written at the end, The front with ... Identification, from the running results, we can know that the passed parameters are bound A, B, and the extra parameters are given to the variable rest in the array form, so we get all the parameters no longer needed arguments. It does not matter if the passed parameters are not filled with the normal defined parameters, and the rest parameter receives an empty array (note that it is not undefined).
Watch your return statement.
function foo () { return;//automatically adds a semicolon, equivalent to return undefined; {name: ' foo '}; This line of statement has been unable to execute the correct notation function foo () { return { name: ' foo ' };}
JavaScript functions define and Invoke