First, the function
The package code can be a function of some specific function, may then be repeated by calling the function name
1. Function Definition
funcation function name () {
function body
}
function name () function call
2. function parameters
funcation fun (parameter 1, parameter 2 ...) {
function declarations
}
Fun (argument 1, argument 2 ...)
Modify parameter values in an internal function and does not affect the value of the external argument
Prime number (and only by themselves divisible 1)
3. return function return value
When the value of the function does not write return when the return is undefined
wrote back did not return with the specific value is also returns undefined
4. arguments
Can get the function call when the arguments by arguments, (when the number of arguments uncertain)
function getMax() { var max = arguments[0]; for (var i = 0; i<arguments.length; i++) { if (max < arguments[i]) { max = arguments[i]; } } return max; } var retult = getMax(23,53,22,35,222,33,553); console.log(retult);
Seeking Fibonacci number in the n-th number is how much?
function getFib(n) { var n1 =1; var n2 =1; var n3; for (var i = 3; i<=n; i++) { n3 = n1 + n2; n1 = n2; n2 = n3; } return n3; } var num = getFib(6); console.log(num);
Second, the anonymous function
1. anonymous function declarations
1. function declarations - command function function Fn () { } 2 function expressions - anonymous function var Fn = function () { }
2. Usage
1 . Assign an anonymous function to a variable so that it can be invoked by variable 2 anonymous function call itself. Since calling a function: When the function call is completed writing immediately ( function () { console.log ( 'I am self-calling function' ) }) () 3 . function is also a data type var Fn = function () { the console.log ( 'I was passed over function' ) } function Test (Fun) { Fun (); } Test (Fn);
3.1 because the function is a data type as a parameter can be another function of 3.2 because the function is a data type, the function as a return value of a function of another function Test (a) { var B =. 5 ; return function () { console.log(a + b); } } var fn = test(2); fn();
Code specification:
1 . Naming rules variable named function to be meaningful variable names generally noun name is generally a function of the verb 2 . VARSPEC operators include a space before and 3 . Note specification // this is a comment 4 . Specification space if and for before and after the parentheses must have space behind the semicolon should have a space 5 . wrap specification braces to keep the definition of starting in a row