day4 js array & Function & Scope

1. array

1.1 create

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        // 1. array: an elegant way to store a set of data under a single variable 
        // 2. create an array with new
        var arr = new Array(); // Created an empty array
        // 3. use array literal to create array []
        var arr = []; // Created an empty array
        var arr1 = [1, 2, 'pink teacher', true];
        // 4. the data in our array must be separated by commas
        // 5. the data in the array, such as 1 and 2, are called array elements
        // 6. get array element format array name [index number] index number starts from 0 
        console.log(arr1);
        console.log(arr1[2]); // Teacher pink
        console.log(arr1[3]); // true
        var arr2 = ['Delireba', 'Gulizana', 'Tong Liya'];
        console.log(arr2[0]);
        console.log(arr2[1]);
        console.log(arr2[2]);
        console.log(arr2[3]); // Because there is no such array element, the output result is undefined
    </script>
</head>

<body>

</body>

</html>

1.2 traversal

    <script>
        // Traversing an array: to access the elements of the array from beginning to end
        var arr = ['red', 'green', 'blue'];
        for (var i = 0; i < 3; i++) {
            console.log(arr[i]);
        }
        // 1. since our array index number starts from 0, i must start from 0 i < 3
        // 2. when outputting, the arr[i] I counter is used as the index number
    </script>

length

    <script>
        // Array length array name Length
        var arr = ['Guan Yu', 'Zhang Fei', 'Machao', 'Zhao Yun', 'Huangzhong', 'Liu Bei', 'Jiang Wei', 'pink'];
        for (var i = 0; i < 7; i++) {
            console.log(arr[i]);
        }
        console.log(arr.length);
        for (var i = 0; i < arr.length; i++) {
            console.log(arr[i]);
        }
        // 1. the length of the array is the number of elements. Do not confuse it with the index number
        // 2. arr.length dynamically monitors the number of array elements
    </script>

case

    <script>
        // 1. find the sum and average value of all elements in the array [2,6,1,7, 4].
        // (1) Declare a sum variable sum.
        // (2) Traverse the array and add each array element to sum.
        // (3) Divide the sum variable sum by the length of the array to get the average value of the array.
        var arr = [2, 6, 1, 7, 4];
        var sum = 0;
        var average = 0;
        for (var i = 0; i < arr.length; i++) {
            sum += arr[i]; // We added array element arr[i] instead of counter I
        }
        average = sum / arr.length;
        console.log(sum, average); // To output multiple variables, separate them with commas
    </script>
    <script>
        // Find the maximum value in the array [2,6,1,77,52,25,7]
        // Declare a variable max that holds the largest element.
        // The default maximum value can take the first element in the array.
        // Traverse the array and compare each array element with max.
        // If the array element is larger than max, save the array element in Max, otherwise continue the next round of comparison.
        // Finally, output this max
        var arr = [2, 6, 1, 77, 52, 25, 7, 99];
        var max = arr[0];
        for (var i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        console.log('The maximum values in this array are:' + max);
    </script>
    <script>
        // Convert the array ['red','green','blue','pink'] to a string and split it with | or other symbols
        // 1. a new variable is required to store the converted String str.
        // 2. traverse the original array, take out the data inside and add it to the string.
        // 3. at the same time, add an additional separator after it
        var arr = ['red', 'green', 'blue', 'pink'];
        var str = '';
        var sep = '*';
        for (var i = 0; i < arr.length; i++) {
            str += arr[i] + sep;
        }
        console.log(str);
    </script>

2. new element

    <script>
        // 1. add an array element and modify the length 
        var arr = ['red', 'green', 'blue'];
        console.log(arr.length);
        arr.length = 5; // Change the length of our array to 5. There should be 5 elements in it 
        console.log(arr);
        console.log(arr[3]); // undefined
        console.log(arr[4]); // undefined

        // 2. add an array element, modify the index number, and add an array element
        var arr1 = ['red', 'green', 'blue'];
        arr1[3] = 'pink';
        console.log(arr1);
        arr1[4] = 'hotpink';
        console.log(arr1);
        arr1[0] = 'yellow'; // Here is to replace the original array elements
        console.log(arr1);
        arr1 = 'Interesting';
        console.log(arr1); // Do not directly assign values to the array name, otherwise the array elements inside will be lost
    </script>

2.1 cases

    <script>
        // Create a new array containing 10 integers (1~10)
        // Core principle: use loop to append array.
        // 1. Declare an empty array arr.
        // 2. The counter i in the loop can be stored as an array element.
        // 3. Since the index number of the array starts from 0, it is more appropriate for the counter to start from 0, and the stored array elements should be +1.
        var arr = [];
        for (var i = 0; i < 100; i++) {
            // arr = i; Do not directly assign values to the array name, otherwise the previous elements will be lost
            arr[i] = i + 1;
        }
        console.log(arr);
    </script>

2.2 screening

    <script>
        // Select the elements greater than or equal to 10 in the array [2, 0, 6, 1, 77, 0, 52, 0, 25, 7] and put them into the new array.
        // 1. Declare a new array to hold the new data newArr.
        // 2. Traverse the old array to find elements greater than or equal to 10.
        // 3. Append to the new array newArr in turn.
        // Method 1
        var arr = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7];
        var newArr = [];
        var j = 0;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] >= 10) {
                // New array index numbers should be incremented from 0
                newArr[j] = arr[i];
                j++;
            }
        }
        console.log(newArr);
        // Method 2 
        var arr = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7];
        var newArr = [];
        // Newarr Length is 0
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] >= 10) {
                // New array index numbers should be incremented from 0
                newArr[newArr.length] = arr[i];
            }
        }
        console.log(newArr);
    </script>

3. array cases

Flip array

    <script>
        // Reverse the contents of the array ['red','green','blue','pink','purple']
        // 1. Declare a new array newArr
        // 2. Take the fourth index number of the old array (arr.length - 1) and give the zero element of the new array index number (newArr.length)
        // 3. We take a decreasing approach i--
        var arr = ['red', 'green', 'blue', 'pink', 'purple', 'hotpink'];
        var newArr = [];
        for (var i = arr.length - 1; i >= 0; i--) {
            newArr[newArr.length] = arr[i]
        }
        console.log(newArr);
    </script>

Bubble sort

    <script>
        // Bubble sort
        // var arr = [5, 4, 3, 2, 1];
        var arr = [4, 1, 2, 3, 5];
        for (var i = 0; i <= arr.length - 1; i++) { // Number of outer circulating pipe trips 
            for (var j = 0; j <= arr.length - i - 1; j++) { // Exchange times of each round of circulating pipe inside
                // Internally exchange the values of two variables. Compare the previous and the following array elements
                if (arr[j] < arr[j + 1]) {
                    var temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }

            }
        }
        console.log(arr);
    </script>

4. function

4.1 concept

    <script>
        // 1. find the cumulative sum of 1~100
        var sum = 0;
        for (var i = 1; i <= 100; i++) {
            sum += i;
        }
        console.log(sum);

        // 2. find the cumulative sum of 10~50
        var sum = 0;
        for (var i = 10; i <= 50; i++) {
            sum += i;
        }
        console.log(sum);

        // 3. a function encapsulates a code block that can be called repeatedly for the purpose of reusing a large amount of code
        function getSum(num1, num2) {
            var sum = 0;
            for (var i = num1; i <= num2; i++) {
                sum += i;
            }
            console.log(sum);
        }
        getSum(1, 100);
        getSum(10, 50);
        getSum(1, 1000);
    </script>

4.2 use


    <script>
        // Function use is divided into two steps: declaring a function and calling a function
        // 1. declaring functions
        // Function function name (){
        //     //Function body
        // }
        function sayHi() {
            console.log('hi~~');

        }
        // (1) function declares that the keywords of a function are all lowercase
        // (2) A function is to do something. The name of the function is usually the verb sayHi 
        // (3) Functions do not call and do not execute themselves
        // 2. call function
        // Function name ();
        sayHi();
        // Do not forget to add parentheses when calling a function
    </script>

4.3 functions with parameters

Row and argument

    <script>
        // 1. the function can repeat the same code
        // function cook() {
        //     Console Log ('hot and sour potato shreds');

        // }
        // cook();
        // cook();
        // 2. we can use function parameters to repeat different codes
        // Function function name (formal parameter 1, formal parameter 2...) {/ / formal parameters (formal parameters) are in the parentheses of the declared function

        // }
        // Function name (argument 1, argument 2...)// Inside the parentheses of the function call are the arguments (actual parameters)
        // 3. execution process of formal and actual parameters
        function cook(aru) { // The formal parameter is aru that accepts the argument = 'hot and sour potato shreds'. The formal parameter is similar to a variable
            console.log(aru);

        }
        cook('Hot and sour potato shreds');
        cook('Big elbow');
        // 4. the number of function parameters may or may not be unlimited
    </script>

example

    <script>
        // 1. use function to find the sum of any two numbers
        function getSum(num1, num2) {
            console.log(num1 + num2);

        }
        getSum(1, 3);
        getSum(3, 8);
        // 2. use the function to find the sum between any two numbers
        function getSums(start, end) {
            var sum = 0;
            for (var i = start; i <= end; i++) {
                sum += i;
            }
            console.log(sum);

        }
        getSums(1, 100);
        getSums(1, 10);
        // 3. precautions
        // (1) Multiple parameters are separated by commas
        // (2) Formal parameters can be regarded as undeclared variables
    </script>

Number of formal and actual parameters match

    <script>
        // Number of function formal and actual parameters match
        function getSum(num1, num2) {
            console.log(num1 + num2);

        }
        // 1. if the number of actual parameters is consistent with the number of formal parameters, the result will be output normally
        getSum(1, 2);
        // 2. if the number of arguments is more than the number of formal parameters, the number of formal parameters will be obtained 
        getSum(1, 2, 3);
        // 3. if the number of actual parameters is less than the number of formal parameters and more than the number of formal parameters is defined as undefined, the final result is NaN
        // Formal parameters can be regarded as undeclared variables. num2 is a variable but does not accept values. The result is undefined 
        getSum(1); // NaN
        // It is suggested that we try to match the number of arguments with the formal parameters
    </script>

4.4 return value

    <script>
        // 1. function is to do something or realize a function
        // function cook(aru) {
        //     console.log(aru);

        // }
        // cook('Big elbow ');
        // 2. return value format of function
        // Function function name (){
        //     return the result to be returned;
        // }
        // Function name ();
        // (1) Our function only implements a certain function. The final result needs to be returned to the caller of the function. The function name () is implemented through return
        // (2) As long as the function encounters a return, it will return the following result to the caller of the function. Function name () = the result after return
        // 3. code verification
        function getResult() {
            return 666;
        }
        getResult(); // getResult()   = 666
        console.log(getResult());

        // function cook(aru) {
        //     return aru;
        // }
        // Console Log (cook ('Big elbow ');
        // 4. sum any two numbers
        function getSum(num1, num2) {
            return num1 + num2;
        }
        console.log(getSum(1, 2));
    </script>

case

    <script>
        // Using function to find the maximum value of two numbers
        function getMax(num1, num2) {
            // if (num1 > num2) {
            //     return num1;
            // } else {
            //     return num2;
            // }
            return num1 > num2 ? num1 : num2;
        }
        console.log(getMax(1, 3));
        console.log(getMax(11, 3));
    </script>
    <script>
        // Use the function to find the maximum value in the array [5,2,99101,67,77].
        function getArrMax(arr) { // Arr accepts an array arr = [5,2,99101,67,77]
            var max = arr[0];
            for (var i = 1; i <= arr.length; i++) {
                if (arr[i] > max) {
                    max = arr[i];
                }
            }
            return max;
        }
        // getArrMax([5, 2, 99, 101, 67, 77])// The argument is an array
        // In our actual development, we often use a variable to accept the return result of the function, which is easier to use
        // var re = getArrMax([5, 2, 99, 101, 67, 77]);
        var re = getArrMax([3, 77, 44, 99, 143]);
        console.log(re);
    </script>

matters needing attention

    <script>
        // Function return value considerations
        // 1. return stop function
        function getSum(num1, num2) {
            return num1 + num2; // return the following code will not be executed
            alert('I will not be executed!')
        }
        console.log(getSum(1, 2));
        // 2. return can only return one value
        function fn(num1, num2) {
            return num1, num2; // The result returned is the last value
        }
        console.log(fn(1, 2));

        // 3. we find the result of addition and subtraction multipliers of any two numbers
        function getResult(num1, num2) {
            return [num1 + num2, num1 - num2, num1 * num2, num1 / num2];
        }
        var re = getResult(1, 2); // Returns an array
        console.log(re);
        // 4. if our function has a return, it returns the value after the return. If the function does not have a return, it returns undefined
        function fun1() {
            return 666;
        }
        console.log(fun1()); // Back 666
        function fun2() {

        }
        console.log(fun2()); // Function returns undefined
    </script>

4.5 arguments

    <script>
        // The use of arguments only functions have arguments objects, and each function has built-in arguments
        function fn() {
            // Console Log (arguments)// It stores all the passed arguments arguments = [1,2,3]
            // console.log(arguments.length);
            // console.log(arguments[2]);
            // We can iterate through arguments as an array
            for (var i = 0; i < arguments.length; i++) {
                console.log(arguments[i]);

            }
        }
        fn(1, 2, 3);
        fn(1, 2, 3, 4, 5);
        // Pseudo arrays are not real arrays
        // 1. have the length attribute of array
        // 2. stored by index
        // 3. it does not have some methods of real arrays, such as pop() push()
    </script>

example

    <script>
        // Using function to find the maximum value of any number
        function getMax() { // arguments = [1,2,3]
            var max = arguments[0];
            for (var i = 1; i < arguments.length; i++) {
                if (arguments[i] > max) {
                    max = arguments[i];
                }
            }
            return max;
        }
        console.log(getMax(1, 2, 3));
        console.log(getMax(1, 2, 3, 4, 5));
        console.log(getMax(11, 2, 34, 444, 5, 100));
    </script>

4.6 mutual calls between functions

    <script>
        // Functions can be called to each other
        // function fn1() {
        //     console.log(11);
        //     fn2()// The fn2 function is called in the fn1 function
        // }
        // fn1();

        // function fn2() {
        //     console.log(22);

        // }

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

        function fn2() {
            console.log(222);
            console.log('fn2');
        }
        fn1();
    </script>

Output days in February case

    <script>
        // The user inputs the year and outputs the days of February in the current year
        function backDay() {
            var year = prompt('Please enter the year:');
            if (isRunYear(year)) { // Parentheses are required for calling functions
                alert('The current year is a leap year. February has 29 days');
            } else {
                alert('The current year is a normal year. February has 28 days');
            }
        }
        backDay();


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

4.7 two function calling methods

        // 2 declaration mode of function
        // 1. use function keywords to customize functions (named functions)
        function fn() {

        }
        fn();
        // 2. function expression (anonymous function) 
        // var variable name = function() {};
        var fun = function(aru) {
            console.log('I am a function expression');
            console.log(aru);

        }
        fun('pink teacher');
        // (1) fun is a variable name, not a function name  
        // (2) Function expressions are declared in the same way as variables, except that values are stored in variables and functions are stored in function expressions
        // (3) Function expressions can also pass parameters
    </script>

5. scope

5.1 general

    <script>
        // 1.JavaScript scope: refers to the function and effect of code names (variables) within a certain range. The purpose is to improve the reliability of the program and, more importantly, to reduce naming conflicts
        // 2. before JS scope (es6): global scope local scope 
        // 3. global scope: the entire script tag or a separate js file
        var num = 10;
        var num = 30;
        console.log(num);

        // 4. local scope (function scope) is the local scope within the function. The name of this code only has effect and effect within the function
        function fn() {
            // Local scope
            var num = 20;
            console.log(num);

        }
        fn();
    </script>

5.2 variable scope

Variable scope: according to different scopes, our variables are divided into global variables and local variables.
From the perspective of execution efficiency, global variables and local variables:
(1) Global variables are destroyed only when the browser is closed, which takes up more memory resources
(2) Local variables will be destroyed after the execution of our program, which saves memory resources

    <script>

        // 1. global variables: variables in the global scope can be used in the global context
        // Note that variables with direct assignment are also global variables if they are not declared inside the function
        var num = 10; // num is a global variable
        console.log(num);

        function fn() {
            console.log(num);

        }
        fn();
        // console.log(aru);

        // 2. local variables are variables within the local scope, and the variables within the function are local variables
        // Note: function parameters can also be regarded as local variables
        function fun(aru) {
            var num1 = 10; // num1 is a local variable that can only be used inside a function
            num2 = 20;
        }
        fun();
        // console.log(num1);
        // console.log(num2);

    </script>

5.3 no block level scope

    <script>
        // js does not have a block level scope. js' scope: global scope local scope at this stage, js does not have a block level scope
        // Our js is also a new block level scope in es6
        // Block level scope {} if {} for {}
        // java 
        // if(xx) {
        //     int num = 10;
        // }
        // You can't call num outside
        if (3 < 5) {
            var num = 10;
        }
        console.log(num);
    </script>

5.4 scope chain

Scope chain: internal functions access variables of external functions and use chain search to determine the value. This structure is called the scope chain proximity principle

    <script>

        var num = 10;

        function fn() { // External function
            var num = 20;

            function fun() { // Internal function
                console.log(num);

            }
            fun();
        }
        fn();
    </script>

case

    <script>
        // Case 1: what is the result?
        function f1() {
            var num = 123;

            function f2() {
                var num = 0;
                console.log(num); // Start from the target and look out layer by layer
            }
            f2();
        }
        var num = 456;
        f1();
        // Case 2: what is the result?
        var a = 1;

        function fn1() {
            var a = 2;
            var b = '22';
            fn2();

            function fn2() {
                var a = 3;
                fn3();

                function fn3() {
                    var a = 4;
                    console.log(a); //Value of a?
                    console.log(b); //Value of b?
                }
            }
        }
        fn1();
    </script>

6. pre analysis

6.1 pre analysis

Our js engine runs js in two steps: pre parsing code execution
(1) The pre parsing js engine will promote all var s and function s in js to the front of the current scope
(2) Code execution is executed from top to bottom in the order of code writing
Pre parsing includes variable pre parsing (variable lifting) and function pre parsing (function lifting)
(1) Variable promotion is to promote all variable declarations to the front of the current scope without promoting the assignment operation
(2) Function promotion is to promote all function declarations to the front of the current scope without calling functions

    <script>
        // 1 question  
        console.log(num);



        // 2 questions
        console.log(num); // undefined Pit 1
        var num = 10;
        // It is equivalent to executing the following code
        // var num;
        // console.log(num);
        // num = 10;



        // 3 questions  
        function fn() {
            console.log(11);
        }
        fn();




        // 4 questions
        fun(); // Error reporting Pit 2 
        var fun = function() {
                console.log(22);

            }
            // Function expression calls must be written below the function expression
            // It is equivalent to executing the following code
            // var fun;
            // fun();
            // fun = function() {
            //         console.log(22);

        //     }

    </script>

6.2 cases

        // //It is equivalent to performing the following operations
        // // var num;

        // // function fun() {
        // //     var num;
        // //     console.log(num);
        // //     num = 20;
        // // }
        // // num = 10;
        // // fun();

        // //Equivalent to the following code
        // // var num;

        // // function fn() {
        // //     var num;
        // //     console.log(num);
        // //     num = 20;
        // //     console.log(num);
        // // }
        // // num = 10;
        // // fn();

        // Equivalent to the following code
        // var a;

        // function f1() {
        //     var b;
        //     var a;
        //     b = 9;
        //     console.log(a);
        //     console.log(b);
        //     a = '123';
        // }
        // a = 18;
        // f1();

        // The following codes
        // function f1() {
        //     var a;
        //     a = b = c = 9;
        //     //Equivalent to var a = 9; B = 9; c = 9; Direct assignment of B and c without var declaration when global variables are viewed
        //     //Collective declaration var a = 9, b = 9, c = 9;
        //     console.log(a);
        //     console.log(b);
        //     console.log(c);
        // }
        // f1();
        // console.log(c);
        // console.log(b);
        // console.log(a);

Reference:

Code one

Code two

Tags: Javascript

Posted by micah1701 on Tue, 31 May 2022 17:50:18 +0530