Day05 - basics of JavaScript functions

function

Function function
Function: put the code of the same function together
Function: encapsulation + reusability

Function classification:
1. System function ()
2. User defined function

Function: it is a tool that can be reused. Some functions have parameters and some do not. Such as math random(),alert(666)

Syntax of function:
Function function name (parameter){
How is the function realized
}
Note: function name (parameter) - the function must be called
The description of the function includes:
1. Function: sum two numbers
2. Parameter Description: (declare the type of parameter)
The first parameter is a number
The second parameter is also a number

Summation by function

        //instructions
        //Function function: find the sum of two numbers
        //Arguments to function:
        //The first parameter is a number
        //The second number is also a number

        //Define a function function function name (parameter)
        function sum(m,n){
            //Print the sum of m,n
            document.write(m+n);
        }
        //Call function
        sum(2,3);

Encapsulation of functions

Steps of function encapsulation:
1. Ordinary to achieve this function
2. Install a shell function
3. Choose a name
4. Consider whether parameters are required - parameters are optional
5. Be sure to call the function
6. Attach instructions

Training: printing triangles using function encapsulation

        function star(m){
            //Outer loop print * lines
            for(var i = 1 ; i <= m ; i++){
                //Inner loop print one line * number
                for(var j = 1 ; j <= i ; j++){
                    //Print*
                    document.write('*')
                }
                //Line feed
                document.write('<br>')
            }
        }

        //Call the function to print the triangle
        star(5) ;

Formal and actual parameters of function:
Where the function is declared: formal parameters
Where the function is called: Arguments

        //Function: print multiplication table
        //Arguments to function:
        //The first parameter is the number number -- print a multiplication table

        // m and n are called formal parameters --- formal parameters
        function multi_99(m , n) {
            for(var i = 1 ; i <= m ; i++){
                for(var j = 1 ; j <= i ; j++){
                    if(n === '*'){
                        document.write(j + '*' + i + '=' + i * j + '&nbsp;&nbsp;&nbsp;');
                    }
                    else if(n === '+'){
                        document.write(j + '+' + i + '=' + (i + j) + '&nbsp;&nbsp;&nbsp;' );
                    }
                }
                document.write('<br>');
            }
        }

        //5 6 * + called actual parameter -- actual parameter
        multi_99(5 , '*');

        multi_99(6 , '+ ');

Training: use the encapsulation of function to output prime numbers within 1-100 and wrap lines

        //Function function: output prime numbers within 100 and wrap lines
        //The first parameter is number -- number. Enter a prime number within 0-A few
        //The second parameter is number -- number. Enter several numbers and change one line
        function isZhi(n , m){

            //First traverse the number of 1-100
            var count = 0 ;
            for(var i = 2 ; i <= n ; i++){
                //Find a prime number that satisfies the condition, assuming it is a prime number
                var flag = true;
                //Find evidence of no - not as long as it can be divided by any number
                for(var j = 2 ; j < i ; j++){
                    //As long as it can be divided by other numbers
                    if(i % j === 0){
                        //The explanation is not a prime number, that is, the hypothesis is overturned
                        flag = false ;
                        //The results have come out, there is no need to continue to look for evidence
                        break ;
                    }
                }

                //Finally, judge whether it is a prime number according to the value of flag
                //flag ? document.write(i) : '';
                if(flag){
                    document.write(i + '&nbsp;&nbsp;');
                    count++;
                    //Wrap every m
                    if(count === m){
                        document.write('<br>');
                        count = 0 ;
                    }
                }
            }
        }

        isZhi(100 , 5);

Return value of function

Return value of function - the result of the final execution of the function
The return value of the function is also optional

When a variable is defined inside a function, it cannot be used outside. An error will be reported because the internal variable of the function cannot be accessed.

        function sum(a , b){
            //Just print the result on the console
            // console.log(a+b);
            var result = a + b ;  
            //result is defined inside the function and cannot be used outside
            // console.log(result);

            return result 
            
        }

        var n = sum(2 , 3) ;
        document.write(n);
        // document.write(result); / / an error is reported because the internal variable of the function cannot be accessed

        var n = Math.random();
        console.log(n); //Function will get a result

        var res = alert(666);
        console.log(res);  //No results show undefined

Training: encapsulating random numbers

        function rand(max , min){

            // var n = Math.round(Math.random()*(max - min) + min) ;
            // return n ;

            return Math.round(Math.random()*(max - min) + min) ;
            //At this time, you need to print outside the function. You must return, otherwise undefined will be displayed
        }

        var m = rand(200,100);
        document.write(m);

Training: judge whether a number is a prime number by using the encapsulation of the function, and output a prime number within 1-100

Insert the code slice here        //Judge whether a genus is a prime number
        function isZhi(x){
            var flag = true ;
            for(var i = 2 ; i < x ; i++){
                if(x % i === 0){
                    flag = false ;
                    break;
                }
            }
            // if (flag){
            //     return true ;
            // }
            //    else{
            //        return false ;
            //    }
            return flag ;
        }

        var r1 = isZhi(12) ; //false
        var r2 = isZhi(17) ; //true
        document.write(r1 , r2) ;



        //All prime numbers within 100
        // for(var i = 2 ; i<= 100 ; i++){
        //     var r4 = isZhi(i);
        //     if(r4){
        //         document.write(i);
        //     }
        // }
        for(var i = 2 ; i <= 100 ; i++) {
            var r4 = isZhi(i) ;
            if(r4) {
                document.write(i)
            }
        }

Training: call the function. 1. Generate a random number within the specified range and judge whether the number is a prime number; 2. Randomly generate two numbers and call the function to sum, difference, multiply and divide.
html code:

<body>
    Generate 100-200 The random numbers between are:<input type="text" id="inp1">
    <br>
    Judge whether he is a prime number:<input type="text" id="inp2">

    <script src="../js/tools_02.js"></script>

    <script>
        //Generate a random number of 100-200 to judge whether it is a prime number

        //Call the function that generates the random number
        var n = rand(100,200)
        //Determine whether the generated random number is a prime number
        var res = isZhi(n) ;
        console.log(n , res)

        //Get object
        var oInp1 = get('inp1');
        var oInp2 = get('inp2');

        oInp1.value = n;

        if(res){
            oInp2.value = 'Is a prime number'
        }
        else{
            oInp2.value = 'Not a prime number'
        }

        
        //The operation of calculating two numbers
        var n1 = rand(0 , 100) ;
        var n2 = rand(0 , 100) ;
        var res2 = jiSuanQi(n1 , n2 , '-') ;
        document.write(n1 + '-' + n2 + '=' + res2);
    </script>
</body>

js code:

//Function: generate random integers in a certain range
//Parameters:
//    Min number range min
//    Max number range Max
//Return value:
//    number
function rand(min , max){
    return Math.round(Math.random()*(max - min) + min)
}

//Judge whether a genus is a prime number
//Parameters:
//     number
//Return value:
//     boolean
function isZhi(x){
    for(var i = 2 ; i < x ; i++){
        if(x % i === 0){
            return false;
        }
    }
    return true;
}

//Get object
function get(id){
    return document.getElementById(id)
}

//Calculator
function jiSuanQi(a , b , f){
    switch(f){
        case '+' : return a + b ;
        case '-' : return a - b ;
        case '*' : return a * b ;
        case '/' : return a / b ;
    }
}

Function notes:

alert(666) calls the function directly and passes a parameter
var n = Math.random() calls the function and accepts the result with a variable
Return value: 1. Result of function execution; 2. End the whole loop in advance
return: end the function ahead of time

Keywords: Javascript ECMAScript

Added by crag on Fri, 10 Dec 2021 18:28:16 +0200