Basic JavaScript learning notes day04

1. Array

1.1 significance and creation of array

  • Array: a collection of data that is stored in a single variable
  • Creation method
		//1. Create an array with new
        var arr = new Array();
        //2. Creating arrays with array literals
        var arr = [];//Common usage
        var arr1 = [1,2,'La La La',true];//The data in the array must be separated by commas
        //3. The data in the array is called elements. The elements in the array can be of any type

1.2 accessing array elements

  • The index (subscript) of the array, which is used to access the sequence number of array elements (starting from 0)
 		var week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
        console.log(week[6]);//Sunday
  • extend
		week.forEach(function(item,index){
            console.log(item);
        });

1.3 traversal array

  • Access the elements in the array from beginning to end
  1. Array name [index number]
		var color = ['red', 'pink', 'blue', 'green','aqua'];
        console.log(color[0]);//Output red
        console.log(color[3]);//Output green
  1. Traversing the array through the for loop index
		for (var i = 0; i < color.length; i++) { //Use "array name. Length" to access the number of array elements (array length)
            console.log(color[i]);
        }
  1. be careful
    • Because array index numbers start at 0, i must start at 0
    • When outputting, i counter is used as index number
    • Here, the length of the array is the number of array elements. Do not confuse it with the index number of the array
    • When the number of elements in our array changes, the * * length attribute changes along with it**
  2. case
		//Sum and average the array
        var sum = 0;
        var num = [2, 6, 1, 7, 4];
        for (var i = 0; i < num.length; i++) {
            sum = sum + num[i];//We added the array element num[i], not the counter
        }
        var average = sum / num.length;
        console.log(`The sum of this array is ${sum}`);//Output 20
        console.log(`The average value of this array is ${average}`);//Output 4
		//Find the maximum value of the array
        var num1 = [2, 6, 1, 77, 52, 25, 7,87,5,95];
        var max = num1[0];
        for(var i = 1; i < num1.length; i++){
            if(num1[i] > max){
                max = num1[i];
            }
        }
        console.log(`The maximum value of this array is ${max}`);//Output 95

1.4 new elements in array

  1. Add a new element in the array and modify the length
		var arr = ['red', 'green', 'blue', 'pink'];
        console.log(arr.length);
        arr.length = 7;//Change the length of our array to 7. There should be 7 elements in it
        console.log(arr);
        console.log(arr[4]);//No assignment. The default is undefined
  1. Adding new elements to the array and modifying index numbers
		arr[4] = 'hotpink';
        arr[5] = 'lightgreen';
        arr[6] = 'aqua';
        console.log(arr[4]);
        console.log(arr[5]);
        console.log(arr[6]);
  1. Note: if the index number is occupied, the original element will be replaced; Do not assign a value to the array name directly, otherwise there will be no array elements in it
  2. case
		//Filter out the numbers greater than or equal to 10 in the array to form a new array
        //Method 1
        var str1 = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7];
        var str2 = [];
        var j = 0
        for(var i = 0; i < str1.length; i++){
            if(str1[i] >= 10){
                //The new array starts at 0 and increases in order
                str2[j] = str1[i];
                j++;
            }
        }
        console.log(str2);//Output array [77,52,25]

        //Method 2
        var str1 = [2,6, 1, 77, 52, 0, 25, 7,34,6];
        var str2 = [];
        for(var i = 0; i < str1.length; i++){
            if(str1[i] >= 10){
                str2[str2.length] = str1[i];//At first, str2.length is 0. After saving a value, the length will change automatically
            }
        }
        console.log(str2);//Output array [77,52,25]

1.5 array cases

  1. Remove 0 from array [2, 0, 6, 1, 77, 0, 52, 0, 25, 7] to form a new array without 0
		var str = [2,0,6,1,77,0,52,0,25,7];
        var newstr = [];
        for(var i = 0; i < str.length; i++){
            if(str[i] != 0){
                newstr[newstr.length] = str[i];
            }
        }
        console.log(newstr);//Output array [2,6, 1,77,52,25,7]
  1. Requirement: store the contents of the array ['red', 'green', 'blue', 'pink', 'purple] in reverse
		var color = ['red', 'green', 'blue', 'pink', 'purple'];
        var newcolor = [];
        for(var i = color.length - 1; i >= 0; i--){//for(var i = 0; i < color.length; i++){
            newcolor[newcolor.length] = color[i]//newcolor[i] = color[color.length - i - 1];
        }//}
        console.log(newcolor);

1.6 bubble sorting

  • Bubble sorting is an algorithm that arranges and displays a series of data in a certain order (from small to large or from large to small)
		var str = [5, 4, 3, 2, 1];
        for (var i = 0; i < str.length - 1; i++) { //Number of outer circulating pipe trips
            for (var j = 0; j < str.length - i - 1; j++) { //Times of inner circulating pipe
                if (str[j] > str[j + 1]) { //Internally exchange the values of two variables, and compare the former with the latter
                    var temp = str[j];
                    str[j] = str[j + 1];
                    str[j + 1] = temp;
                }
            }
        }
        console.log(str);//Output array [1,2, 3,4, 5]

2. Function

2.1 significance and use of function

  • A function encapsulates a block of code that can be repeatedly called and executed. Through this code block, a large amount of code can be reused
  1. Declarative function
		function Function name() {
            Function body code
        }
  • be careful:
    1. Function is the keyword that declares the function and must be lowercase
    2. Since functions are generally defined to implement a function, we usually name the function as a verb, such as getSum
  1. Calling function name ()
		function sayHi(){
            console.log('hi~');
        }
        sayHi();
  1. be careful:
    1. Don't forget to add parentheses when calling
    2. Pithy formula: functions are not called, and they do not execute themselves
    3. Declaring the function itself will not execute the code, and the function body code will be executed only when the function is called
  2. Function case
		//A function that calculates the sum of 1-100
        function getsum(){//Declare a function
            var sum = 0;
            for(var i = 1; i <= 100; i++){
                sum += i;
            }
            console.log(sum);
        }
        getsum();//Call function

2.2 real and formal parameters in functions

  • Definition: when declaring a function, you can add some parameters in parentheses after the function name. These parameters are called formal parameters; When calling this function, you also need to pass the corresponding parameters, which are called arguments
  • Function. Some values cannot be fixed inside the function. We can pass different values when calling the function through parameters
		// Function declaration with arguments
        /* function Function name (formal parameter 1, formal parameter 2, formal parameter 3, etc.) {formal parameters accept arguments, similar to a variable
            Function body
        }
        Function name (argument 1, argument 2, argument 3, etc.); parameters can be or not, unlimited number, separated by commas*/ 
  • case
		//Using function to sum two numbers
        function getsum(num1, num2, num3) {
            console.log(num1 + num2 + num3);
        }
        getsum(4, 8,8);//12
        getsum(5,23);//28

2.3 supplementary function correlation

  • Transfer process of function parameters

    1. When called, the argument value is passed to the formal parameter
    2. Formal parameters are simply understood as variables that do not need to be declared
    3. Multiple parameters of arguments and formal parameters are separated by commas (,)
    • Mismatch between number of the formal and actual parameters of the function

      1. If the number of arguments is the same as the number of formal parameters, the correct result will be output
      2. When the number of arguments is greater than the number of formal parameters, only the number of formal parameters is obtained
      3. When the number of arguments is less than the number of formal parameters, the multiple formal parameters are defined as undefined and the result is NaN
    • Note that in JavaScript, the default value of the formal parameter is undefined

    2.4 return value of function return

    • Return statement to return the value of the function to the caller
		// Declarative function
        /* function Function name (){
            return The value to be returned;
        }
        Function name (); at this time, you can call the function to get the value after return in the function body*/
  • be careful:
    1. When using the return statement, the function stops execution and returns the specified value
    2. If the function does not return, the returned value is undefined
  • case
		//1. Using function to find the maximum of any two numbers
        function getmax(num1,num2){
            return num1 > num2? num1 : num2;
            /* if(num1 > num2){
                return num1;
            }else{
                return num2;
            } */
        }
        console.log(getmax(34,65));  
        console.log(getmax(76,23));
		//2. Using function to find the maximum value in any array
        function getMax(arr){
            var max = arr[0];
            for(var i = 1; i < arr.length; i++){
                if(arr[i] > max){
                    max = arr[i];
                }
            }
            return max;
        }
        var arr1 = [3,5,8,12,54,32,18];
        // var max1 = getMax(arr1);
        // console.log(max1);
        console.log(getMax(arr1));
  • Supplement:
    1. When return is used, the function will stop executing and subsequent statements will not be executed
    2. Return can only return one value. If there are multiple values, the last one will be returned

3. Some cases in operation

  1. Write a function, the user enters a number to judge whether it is a prime number, and returns the pop-up value (also known as prime number, which can only be used by 1 and its own integer)
        var num = +prompt('Please enter a positive integer');
        function getprime(num){
            for(var i = 2; i < num; i++){
                if(num % i == 0){
                    return 'no';
                }
            }
            return 'yes';
        }
        console.log(getprime(num));
  1. Simple calculator, users can choose the calculation method and input numbers
		var choose = prompt('Welcome to the easy Calculator:' + '\n' + '1,Addition calculation;' + '\n' + '2,Subtraction calculation' + '\n' + '3,Multiplication calculation' + '\n' + '4,Division calculation' +'\n' + '5,sign out' + '\n' + 'Please enter your options');
        if (choose == 5) {
            alert('sign out');
        } else {
            var num1 = +prompt('Please enter the first number');
            var num2 = +prompt('Please enter the second number');
            alert(getresult(num1, num2));
        }
        function getresult(num1, num2) {
            if (choose == 1) {
                return num1 + num2;
            } else if (choose == 2) {
                return num1 - num2;
            } else if (choose == 3) {
                return num1 * num2;
            } else if (choose == 4) {
                return num1 / num2;
            }
        }

Tags: Javascript node.js html5

Posted on Sun, 17 Oct 2021 14:18:18 -0400 by eazyGen