JavaScript branch structure, loop structure, and function definition and use, array

JS branch structure

if statement

Same as java

  • if

  • if…else

  • if…else…if

     //Case: Determine the length of the input password
    let pwd = prompt("Please enter password");
        let L = pwd.length;
        if(L<6){<!-- -->
            alert("Password is less than six characters");
        }else if(L>=6 & amp; & amp; L<16){<!-- -->
            alert("Password is greater than 6 characters and less than 16 characters");
        }else if(L>=16){<!-- -->
            alert("Password is greater than 16 characters");
        }
    
switch statement

Same as java: switch…case

var id = 1;
switch(id){<!-- -->
  case 1:
     console.log("Ordinary member");
     break; //Stop? Execute?, jump out of switch
  case 2:
     console.log("VIP member");
     break; //Stop? Execute?, jump out of switch
  case 3:
     console.log("Administrator");
     break; //Stop? Execute?, jump out of switch
  default: //When none of the above conditions are met, the code is executed by default
     console.log("Visitor");
}

Definition and use of JS functions

A function is a block of code designed to perform a specific task. It can be used repeatedly. In addition to the built-in functions, you can also customize functions. Call the function where needed to avoid repeated writing and ensure the later maintenance of the code.

Function definition
  • The function declaration in JavaScript must start with the function keyword, followed by the name of the function to be created. The function keyword must be written as ?

  • Separate spaces between function keyword and function name

  • The number of parameters can be any number

    When a parameter is given a default value and no parameters are passed when calling, the default value will be used as the parameter.

  • Write function body in {}

Syntax format

function function name (parameter){<!-- -->
    //Function body
}
  1. function without parameters

    The number of parameters is 0;

    function sayHi(){<!-- -->
        console.log("hello,Everybody~");
    }
    
  2. function with parameters

    The number of parameters is not 0

    function sayHi(str){<!-- -->
        console.log(str);
    }
    
    sayHi("Hello"); //Call and pass parameters
    
Function return value
  • When the function is executed, it is often not necessary to print out the result. Instead, we hope that the function will return a result value (for example, if the calculation result is returned before subsequent calculations are performed), the returned result value is called “return value”
  • Return a return value through return in a function
  • The return value can be of any type, such as string, number, array, object, etc.
  • The returned result can be printed directly, or a variable can be used to accept the return value of this function.
Function expression

Another way to declare functions

Keyword variable name (function name) = function (parameter){<!-- -->
    //Function body
}
//Example
var getSum = function(num1,num2){<!-- -->
    var sum = num1 + num2;
    return sum;
}
 console.log(getSum(10,20));
Anonymous function

It’s a function without a name

  1. If you only write an anonymous function, an error will be reported if it does not meet the grammatical requirements, so you need to wrap the anonymous function with () to make it an expression.

  2. The content enclosed by ? brackets will be recognized by js as an expression.

    //Method 1
    (function(){<!-- -->
        alert("Prosperity, Democracy, Civilization and Harmony");
    })();
    
    //Method Two
    (function(){<!-- -->
        alert("Freedom, Equality, Justice and Legal System");
    }());
    
Function scope
  1. local scope
    • When a function is run, a local operating domain is formed inside the function. The variables defined in the local operating domain are called local variables.
    • Local variables will be automatically destroyed when the function ends.
    • Variables outside the function can be accessed inside the function, but internal variables cannot be accessed outside the function.
  2. global scope
    • The global scope refers to the window, that is, the current window. The variables defined under the window are called global variables.
    • Global variables are valid in the current file
var num = 1;
function fun(){<!-- -->
    varnum = 2;
    console.log("num in console" + num); //Output 2
}
fun();
alert("num in the pop-up box" + num); //Output 1
================================================== =
{<!-- -->
  var name1 = "Jackie Chan"; //var function scope
  let name2 = "Xiaoyu"; //let block-level scope
}
console.log(name1); //Output Jackie Chan
console.log(name2); //error report

JS array creation

Constructor creates array

Array objects can be used to define arrays

  • values represents a list of elements in an array
  • Commas between multiple elements? Separate
  • If only two parameters are provided, then this array represents the initial size of the array.
var arr = new Array("Big-headed son", "Small-headed father", "Apron mother");
 console.log(arr);
Literal creates array

Directly use ? [] to define the array

var arr = ["The Legend of Rainbow Cat and Blue Rabbit", "The Adventures of Jackie Chan", "The Magic Chef Xiao Fugui", "The Magic Soldier"];

JS loop

Same as in JAVA

while loop

The while loop is suitable for use when conditions are unknown?

while(loop condition){<!-- -->
 //code content
}
do while loop

Execute first and judge later

do{<!-- -->
    //code content
}while(loop condition);
for loop

Suitable for use when the number of cycles is known

Four conditions: initial value (executed only once) loop condition conditional iteration loop statement

for(var i =1;i<10;i + + ){<!-- -->
    document.write(i + " ");
}
break

terminate loop

continue

Jump out of the current loop without affecting the next loop

for in loop

The for in loop is a variant of the ordinary for loop. It is mainly used to traverse the object and loop out the attributes in the object in sequence.

for(variable in Object){<!-- -->
    //Execute code
}
  • variable is a variable. This variable will be assigned a different value each time it loops. You can use the variable in {} to perform a series of operations.

  • Object is the object to be traversed. In each loop, Object will be

    The key of each attribute in the object is assigned to the variable variable until all attributes in the object have been traversed.

for of loop
  1. The for of loop is a new loop format in ES6. It is similar to for in and is also a variant of the ordinary for loop.
  2. Use the for of loop to traverse arrays or other traversable objects, such as strings, objects, etc.
for(variable of iterable){<!-- -->
    //Execute code
}
  • variable is a variable. The variable will be assigned a different value each time it loops. We can use this variable in the following {} to perform a series of operations.
  • iterable is the content to be traversed. In each loop, each value in iterable will be assigned to the variable varible until all the values in iterable have been traversed.

JS array methods

  1. isArray(): Determine whether it is an array
  2. concat(): concatenates two or more arrays and returns the result
  3. pop(): deletes the last element of the array and returns the deleted element
  4. push(): Adds two or more elements to the end of the array and returns the length of the array
  5. shift(): delete and return the ?th element of the array
  6. unshift(): Adds one or more elements to the beginning of the array and returns the length of the array
  7. index0f(): Search for an element in the array and return its location
  8. splice(): Used to add or delete elements in an array
  9. forEach(): Execute the callback function times for each element of the array
  10. map(): Process each element of the array through the specified function and return the processed array

Note

  1. map is faster than foreach
  2. map will return a new array and will not affect the original array; foreach will not return a new array and will return undefined
let arr = ["The Magic Chef Xiao Fugui", "The Adventures of Jackie Chan", "The Magic Soldier", "The Legend of Nezha", "The Legend of Rainbow Cat and Blue Rabbit"];
    let arr1 = [1,2,3,4,5];
    let arr2 = ["Passbook","General Yu"];
    
    // let result = Array.isArray(a);
    // let result = arr.pop();
    // let result = arr.push("The Adventures of Lolo");
    // let result = arr.shift();
    // let result = arr.unshift("Fruit Special Attack");
    // let result = arr.indexOf("The Adventures of Jackie Chan")
    // let result = arr.indexOf("The Adventures of Little Carp")
    // let result = arr.concat(arr1);
    // let result = arr1.concat(arr);
    // let result = arr.concat(arr1,arr2); //Multiple string concatenation
    // let result = arr.splice(1,1);
    // let result = arr.splice(2);
    // let result = arr.splice(1,1,"Chanel");
    // let result = arr.splice(1,1,"Gucci","Zumalon");
    
    // console.log(result);
    // console.log(arr);


    // let result = arr.forEach(
    // function(value, index, oldarr){<!-- -->
    // // console.log(value + "===" + index + "===" + oldarr);
    // return value,index,oldarr;
    // }
        
    // )

    // let result = arr.map(
    // function(value,index,oldarr){<!-- -->
    // // console.log(value + "===" + index + "===" + oldarr);
    // return value,index,oldarr;
    // }
    // )
    console.log(result);