Introduction of a function
1. The concept: a bunch of code in accordance with certain rules, make up to achieve a certain function, call the function itself or by event
Function features:
Ignore the details: only concerned with the function of its implementation, does not care about the internal structure;
Reuse: function code reuse may be implemented;
Choose to use: only when the function is executed, the function code to run, do not perform that is not running.
function fn(a){ console.log(a); //5 } fn(5);
Number of parameters: You can pass an unlimited number.
Parameter Type: can be any data type. (When a function as a parameter A, B, passed to another function, is performed as a function of the A parameter, called callback)
Relationship: arguments and parameters, consistent with the number, in accordance with the order of one to one (multi-parameter, multi-parameter out is undefined; multiple arguments, the extra argument, arguments are passed to the object)
function fn(b,a,c){ console.log(a); //world console.log(b); //hello console.log(c); //123 console.log(argument); //Argument{0:"hello",1:"world",2:123,3:456,4:789} } fn("hello","world",123,456,789) ;
argument: is a dummy array having a length and an index; can get by traversing all the arguments.
The return value of the function
Return Value: after the function is executed, the data obtained, execution returns to the statement function.
(By default, the function returns undefined, the return value if there is need to use the keyword in a function: return)
function fn(){ console.log(a); //f2 var a = "hello"; console.log(a); //"hello" function a(){1} console.log(a); //"hello" a = "world"; console.log(a); //"world" function a(){2} console.log(a); //"world" } fn(); // This code is equivalent to ↓↓↓ function Fn () { var A; function A (). 1 { } function A () {2 } console.log(a); //f2 a = "hello"; console.log(a); //"hello" console.log(a); //"hello" a = "world"; console.log(a); //"world" console.log(a); //"world" } fn();
3. recursive functions: the implementation of their own in the function (recursive most important thing is to stop condition)
// factorial 10 recursive function Fn (n-) { IF (n-==. 1 ) { return . 1 } the else { return n-Fn * (n--. 1 ) } } console.log(fn(10))
// use recursion Fibonacci number (1,1,2,3,5,8,13,21,34,55,89 ...) function Fn (n-) { IF (n-==. 1 || 2 == n- ) { return . 1 } the else { return Fn (. 1-n-) + Fn (2-n- ) } } console.log(fn(5))
4. Constructor
Constructors: not a function is a way of creating a data function to perform.
// create a numeric data: var n-= new new Number The (123 ); // Create character data: var S = new new String ( "Hello");