JavaScript knowledge points sorting - function

catalogue

1, Concept of function

2, Use of functions

2.1 function declaration

2.2 calling functions

2.3 function encapsulation

3, Parameters of function

3.1 formal parameters and arguments

3.2 mismatch between the number of function formal parameters and real parameters

4, Return value of function

4.1 return statement

4.2 return termination function

4.3 return value

4.4 the function returns undefined without return

4.5 difference between break, continue and return

5, Use of arguments

6, Two ways to declare functions

6.1 using function keywords to customize functions (named functions)

6.2 function expression (anonymous function)

7, Case exercise

7.1 flip any array by function encapsulation

7.2 # use function encapsulation to sort arrays - bubble sort

7.3 using function - to judge leap years

7.4 function calling another function

7.5 input the year and output the number of days in February of the current year

1, Concept of function

Function: encapsulates a code block that may be repeatedly called and executed. Through this code block, a large amount of code can be reused

2, Use of functions

2.1 function declaration

    // Declarative function
    function Function name() {
        // Function body code
    }
  • Function is the keyword that declares the function and must be lowercase
  • Functions are generally defined to achieve a certain function, so they are usually named after verbs

2.2 calling functions

    // Call function
    Function name(); // Execute the function body code by calling the function
  • Don't forget to add parentheses when calling
  • Declaring the function itself does not execute the code, and the function is executed only when the function is called

2.3 function encapsulation

  • Function encapsulation is to encapsulate one or more functions through functions, and only provide a simple function interface

3, Parameters of function

3.1 formal parameters and arguments

When declaring a function, you can add some parameters in parentheses after the function name. These parameters are called formal parameters. When calling the function, you also need to pass corresponding parameters, which are called arguments

parameterexplain
Formal parameterFormal parameters. The parameters passed during function definition are unknown at present
ArgumentIn fact, parameters are passed during function calls, and arguments are passed to formal parameters

3.2 mismatch between the number of function formal parameters and real parameters

Number of parametersexplain
The number of arguments is equal to the number of formal parametersThe output result is correct
The number of arguments is more than the number of formal parametersOnly get the number of formal parameters
The number of arguments is less than the number of formal parametersMultiple formal parameters are defined as undefined and the result is NaN
  • In JavaScript, the default value of the formal parameter is undefine

4, Return value of function

4.1 return statement

Function return value format

    function Function name(){
        return Results to be returned;
    }
  • The function only implements a certain function. The final result needs to be returned to the caller of the function. The function name () is realized through return
  • As long as the function encounters a return, it will return the following result to the function caller. Function name () = the result after return

4.2 return termination function

The code after the return statement is not executed

4.3 return value

Return can only return one value. If multiple values are separated by commas, the last one shall prevail.

4.4 the function returns undefined without return

All functions have return values

  1. If there is a return, return the value after the return
  2. If there is no return, return undefined

4.5 difference between break, continue and return

  • break: end the current loop (e.g. for, while)
  • Continue: jump out of this cycle and continue to execute the next cycle (such as for and while)
  • Return: it can not only exit the loop, but also return the value in the return statement. At the same time, it can also end the code in the current function body

5, Use of arguments

When we are not sure how many parameters are passed, we can use arguments to get them. In JavaScript, arguments is actually a built-in object of the current function. All functions have a built-in arguments object, which stores all the arguments passed

arguments is displayed as a pseudo array, so it can be traversed. Pseudo arrays have the following characteristics:

  • With length attribute
  • Store data by index
  • push, pop and other methods without array

6, Two ways to declare functions

6.1 using function keywords to customize functions (named functions)

    function fn(){

    }
    fn();

6.2 function expression (anonymous function)

    // var variable name = function() {};
    var fun = function(value) {
        console.log('Function expression');
        console.log(value);
    }
    fun('Argument');
  • fun is a variable name, not a function name
  • The declaration method of function expression is similar to that of variable declaration, except that the value is stored in the variable and the function is stored in the function expression
  • Function expressions can also pass parameters

7, Case exercise

7.1 flip any array by function encapsulation

    function reverse(arr) {
        var newArr = [];
        for (var i = arr.length - 1; i >= 0; i--) {
            newArr[newArr.length] = arr[i];
        }
        return newArr;
    }
    var arr1 = reverse([5,4,2,1,3]);
    console.log(arr1);
    var arr2 = reverse(['red','blue','green']);
    console.log(arr2);

7.2 # use function encapsulation to sort arrays - bubble sort

    function sort(arr) {
        for (var i = 0; i <= arr.length - 1; i++){ //Number of cycles of outer circulating pipe
            for (var j = 0; j <= arr.length - i -1; j++){ //Exchange times of inner layer circulating pipe per trip
                //Internally exchange the values of two variables, and compare the former with the latter array element
                if (arr[j] > arr[j+1]){
                    var temp =arr[j];
                    arr[j] = arr[j+1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;   
    }
    var arr1 = sort([1,5,6,4,3]);
    console.log(arr1);

7.3 using function - to judge leap years

    function isRunYear(year) {
        var flag = false;
        if (year % 4 ==0 && year % 100 !=0 || year % 400 ==0){
            flag = true;
        }
        return flag;
    }
    console.log(isRunYear(2004));
    console.log(isRunYear(1997));

7.4 function calling another function

    function fn1() {
        console.log(1);
        fn2();
        console.log('fn1');
    }
    function fn2() {
        console.log(2);
        console.log('fn2');
    }
    fn1();

7.5 input the year and output the number of days in February of the current year

    function backDay(){
        var year = prompt('Please enter the year:');
        if (isRunYear(year)){
            alert('The current year is a leap year, with 29 days in February')
        } else {
            alert('The current year is a normal year, with 28 days in February')
        }
    }
    backDay();

    // Function to judge whether it is a leap year
    function isRunYear(year) {
        var flag = false;
        if (year % 4 ==0 && year % 100 !=0 || year % 400 ==0){
            flag = true;
        }
        return flag;
    }

 

 

Keywords: Javascript Front-end

Added by onlinegs on Sat, 12 Feb 2022 12:11:41 +0200