Web front end learning notes 11: JavaScript_ Notes_ Input and output_ Variable_ Data type_ Keywords_ Reserved word_ Operator_ Process control

Posted by timcclayton on Fri, 24 Dec 2021 11:12:19 +0100

JavaScript Foundation Day 01

1 - Programming Language

1.1 programming

  • Programming:
    • Is to let the computer use a programming language to write program code to solve a problem, and finally get the result.
  • Computer program:
    • It is a series of instructions executed by the computer, and all the programs are written in the language we master, so people must send commands to the computer through the computer language if they want to control the computer.

1.2 computer language

  • Computer language refers to the language used for communication between people and computers. It is the medium for transmitting information between people and computers.

  • There are many kinds of computer languages. Generally speaking, they can be divided into three categories: machine language, assembly language and high-level language.

  • In fact, the final execution of the computer is machine language. It is a binary number composed of "0" and "1". Binary is the basis of computer language.

1.3 programming language

programing language:
	We can control the computer through a "language" similar to human language and let the computer do things for us. Such a language is called programming language( Programming Language). Programming language is a series of instructions used to control the computer. It has fixed format and vocabulary (the format and vocabulary of different programming languages are different), which must be observed. Today, there are two common programming languages: assembly language and high-level language.
Language typeexplain
assembly languageAssembly language and machine language are essentially the same. They operate directly on hardware, but the instructions use English abbreviation identifiers, which are easy to identify and remember.
high-level languageCompared with low-level languages, high-level languages do not specifically refer to a specific language, but include many programming languages, such as C language, C + +, Java, c#, Python, PHP, JavaScript, Go language, Objective-C, Swift, etc.

1.4 translator

	The program written in high-level language can not be directly recognized by the computer, and can only be executed after conversion. Therefore, we need a translator. The translator can convert the source code we write into machine language, which is also called binarization.

1.5 differences between programming language and markup language

languageexplain
programing languageProgramming language has strong logic and behavior ability. In the programming language, you will see many if, else, for, while and other logical and behavioral instructions, which are active.
Markup LanguageMarkup language (html) is not used to issue instructions to computers, but is often used for formatting and linking. The existence of markup language is used to be read, and it is passive.

summary

  1. Computers can help humans solve some problems
  2. Programmers use programming language to write programs and send instructions to control the computer to realize these tasks
  3. Programming languages include machine language, assembly language and high-level language
  4. A high-level language requires a translator to convert it into a machine language recognized by the computer
  5. Programming language is active and has strong logic

2 - Fundamentals of computer

2.1 computer composition

2.2 data storage

  1. The computer internally uses binary 0 and 1 to represent data.
  2. All data, including files and pictures, are finally stored in the hard disk in the form of binary data (0 and 1).
  3. All programs, including the operating system, are essentially all kinds of data, which are also stored in the hard disk in the form of binary data. Usually what we call installing software is actually copying the program files to the hard disk.
  4. Hard disk and memory are stored binary data.

2.3 data storage unit

Size relationship: bit < byte < kb < GB < TB<.....
  • Bit: 1 bit can store a 0 or 1 (the smallest storage unit)
  • Byte: 1B = 8b
  • Kilobytes (KB): 1KB = 1024B
  • Megabytes (MB): 1MB = 1024KB
  • Gigabyte (GB): 1GB = 1024MB
  • Terabyte (TB): 1TB = 1024GB

2.4 program operation

The process of running software on the computer:
1. When opening a program, first load the program code from the hard disk into memory
2. CPU Execute code in memory
   Note: an important reason for memory is because cpu It runs too fast. If you only read data from the hard disk, it will be wasted cpu Performance, so we use memory with faster access speed to save run-time data. (memory is electric, hard disk is mechanical)

3 - initial JavaScript

3.1 what is JavaScript

  • JavaScript is one of the most popular languages in the world. It is a scripting language running on the client (Script means Script)
  • Scripting language: no compilation is required. The js interpreter (js engine) interprets and executes it line by line during operation
  • Now it can also be based on node JS technology for server-side programming

3.2 role of JavaScript

  • Form dynamic verification (password strength detection) (the original purpose of JS generation)
  • Web effects
  • Server development (Node.js)
  • Desktop program (Electron)
  • App(Cordova)
  • Control hardware - Internet of things (Ruff)
  • Game development (cocos2d JS)

3.3 relationship between HTML / CSS / JS

3.4 introduction to JS execution by browser

The browser is divided into two parts: rendering engine and JS engine

	The browser itself does not execute JS Code, but through built-in JavaScript engine(interpreter) To execute JS code. JS When the engine executes the code, it explains the source code of each sentence line by line (converted into machine language), and then the computer executes it, so JavaScript Language is classified as script language and will be interpreted and executed line by line.

3.5 composition of JS

  1. ECMAScript

    ECMAScript is a programming language standardized by ECMA International (the former European Computer Manufacturers Association). This language is widely used on the world wide web. It is often called JavaScript or JScript, but in fact, the latter two are the implementation and extension of ECMAScript language.

    ECMAScript: it specifies the programming syntax and basic core knowledge of JS. It is a set of JS syntax industry standards that all browser manufacturers abide by.

    See MDN: MDN manual

  2. DOM -- Document Object Model

    Document object model (DOM) is a standard programming interface recommended by W3C organization for handling extensible markup language. Through the interface provided by Dom, various elements on the page can be operated (size, position, color, etc.)

  3. BOM - browser object model

    Browser Object Model (BOM) refers to the Browser Object Model, which provides an object structure that is independent of content and can interact with the browser window. Through BOM, you can operate the browser window, such as pop-up box, control browser jump, obtain resolution, etc.

3.6 JS initial experience

JS There are three writing positions: inline, inline and external.
  1. Inline
<input type="button" value="Let me try" onclick="alert('Hello World')" />
  • You can write a single line or a small amount of JS code in the event attribute of the HTML tag (the attribute starting with on), such as onclick
  • Note the use of single and double quotation marks: we recommend using double quotation marks in HTML and single quotation marks in JS
  • Poor readability, inconvenient to read when writing a large amount of JS code in html;
  • Quotation marks are easy to make mistakes. When quotation marks are nested and matched in multiple layers, they are very easy to be confused;
  • Use under special circumstances
  1. embedded

    <script>
        alert('Hello  World~!');
    </script>
    
    • You can write multiple lines of JS code to the script tag
    • Embedded JS is a common way of learning
  2. External JS file

    <script src="my.js"></script>
    
    • It is conducive to the structure of HTML page code, and a large section of JS code is independent of HTML page, which is not only beautiful, but also convenient for file level reuse
    • No code can be written in the middle of the script tag that references the external JS file
    • It is suitable for a large amount of JS code

4 - JavaScript comments

  • Shares of flex sub projects
  • Align self controls how children are arranged on the side axis
  • The order attribute defines the order in which the children are arranged (before and after)

4.1 single line notes

In order to improve the readability of the code, JS And CSS Similarly, annotation is also provided.
JS There are two main types of comments in: single line comments and multi line comments.

Single line notes are annotated as follows:

// I'm a line of text. I don't want to be executed by the JS engine, so I annotate it	
// Used to annotate single line text (Shortcut ctrl + /)

4.2 multiline notes

Multiline comments are annotated as follows:

/*
  Get user age and name
  And displayed through the prompt box
*/
/* */  Used to annotate multiline text (default shortcut)  alt +  shift  + a ) 

The shortcut key is changed to ctrl + shift +/

vscode → preference button → keyboard shortcut → find the original shortcut → modify to a new shortcut → enter to confirm

5 - JavaScript input / output statements

In order to facilitate the input and output of information, JS provides some input and output statements. The common statements are as follows:

methodexplainascription
alert(msg)Browser pop-up alert boxbrowser
console.log(msg)Browser console printout informationbrowser
prompt(info)The browser pops up an input box, which can be entered by the userbrowser
  • Note: alert() is mainly used to display messages to users, console Log () is used to show the runtime messages to the programmer.

6 - concept of variables

6.1 what are variables

Vernacular: a variable is a box of things.

Popular: variables are containers for storing data. We get the data through the variable name, and even the data can be modified.

6.2 storage of variables in memory

	Essence: a variable is a piece of space applied by a program in memory for storing data. Similar to our hotel room, a room can be regarded as a variable.  

7 - use of variables

  • Declaration of variables
  • Assignment of variables

7.1 declared variables

//  Declare variable  
var age; //  Declare a variable named age     
  • var is a JS keyword used to declare variables (the meaning of variable). After using this keyword to declare a variable, the computer will automatically allocate memory space for the variable, which does not need to be managed by the programmer

  • age is the variable name defined by the programmer. We need to access the allocated space in memory through the variable name

7.2 assignment

age = 10; // Assign a value of 10 to this variable          
  • =It is used to assign the value on the right to the variable space on the left, which means assignment
  • The variable value is the value that the programmer saves in the variable space

7.3 initialization of variables

var age  = 18;  // The declared variable is also assigned a value of 18
// Declaring and assigning a variable is called variable initialization.

7.4 variable syntax extension

  • Update variable

    After a variable is re assigned, its original value will be overwritten, and the variable value will be subject to the last assigned value.

    var age = 18;
    
    age = 81;   // The end result is 81 because 18 is covered          
    
  • Declare multiple variables at the same time

    When declaring multiple variables at the same time, you only need to write a var, and multiple variable names are separated by English commas.

    var age = 10,  name = 'zs', sex = 2;       
    
  • Declare variable special cases

    situationexplainresult
    var age ; console.log (age);Declare only without assignmentundefined
    console.log(age)No declaration, no assignment, direct usereport errors
    age = 10; console.log (age);No declaration, only assignment10

7.5 variable naming specification

Rules:

  • Consists of letters (A-Za-z), numbers (0-9), underscores () Dollar sign ($), such as usrage, num01_ name
  • Strictly case sensitive. var App; And var App; Are two variables
  • Cannot start with a number. 18age is wrong
  • Cannot be keyword or reserved word. For example: var, for, while
  • Variable names must be meaningful. MMD BBD nl → age
  • Follow the hump nomenclature. The first letter is lowercase, and the first letter of the following word needs to be capitalized. myFirstName

Youdao ICIBA

8 - data type

8.1 introduction to data types

  • Why do I need a data type

    In the computer, the storage space occupied by different data is different. In order to divide the data into data with different memory sizes and make full use of the storage space, different data types are defined.
    Simply put, the data type is the category and model of the data. For example, the name "Zhang San" and age 18 are different types of data.

  • Data type of variable

    Variables are where values are stored. They have names and data types. The data type of a variable determines how bits representing these values are stored in the computer's memory. JavaScript is a weakly typed or dynamic language. This means that there is no need to declare the type of variable in advance. During the program running, the type will be determined automatically:

    var age = 10;        // This is a numeric type
    var areYouOk = 'yes';   // This is a string     
    

    When the code runs, the data type of the variable is determined by the JS engine according to the data type of the variable value on the right. After running, the variable determines the data type. JavaScript has dynamic types, which also means that the same variables can be used as different types:

var x = 6; // x is a number
var x = “Bill”; // X is a string

- Classification of data types

	JS Data types are divided into two categories:

- Simple data type( Number,String,Boolean,Undefined,Null)

- Complex data type( object)	

### 8.2 simple data types

Simple data type (basic data type)

JavaScript The simple data types in and their descriptions are as follows:



- Digital type Number

​		JavaScript Numeric types can hold both integers and decimals(Floating point number).  

```js
var age = 21;       // integer
var Age = 21.3747;  // decimal     
  1. Digital hexadecimal

    The most common base systems are binary, octal, decimal and hexadecimal.

      // 1. Octal digit sequence range: 0 ~ 7
     var num1 = 07;   // Corresponding to decimal 7
     var num2 = 019;  // Corresponding to decimal 19
     var num3 = 08;   // 8 corresponding to decimal
      // 2. Hexadecimal digit sequence range: 0 ~ 9 and A~F
     var num = 0xA;   
    

    At this stage, we only need to remember to add 0 before octal and 0x before hexadecimal in JS

  2. Digital range

    Maximum and minimum values of values in JavaScript

    • Maximum value: number MAX_ Value: 1.7976931348623157e+308

    • Minimum value: number MIN_ Value: 5e-32

  3. Digital three special values

    • Infinity, representing infinity, greater than any value

    • -Infinity, representing infinitesimal, less than any value

    • NaN, Not a number, represents a non numeric value

  4. isNaN

    It is used to judge whether a variable is of non numeric type and returns true or false

  var usrAge = 21;
var isOk = isNaN(userAge);
  console.log(isNum);          // false, 21 is not a non number
var usrName = "andy";
  console.log(isNaN(userName));// true, "andy" is a non number
  • String type string

    String type can be any text in quotation marks, and its syntax is double quotation mark "" and single quotation mark '

    var strMsg = "I Love Beijing Tiananmen ~";  // Use double quotation marks to represent strings
    var strMsg2 = 'I like pig feet~';    // Use single quotation marks to represent strings
    // Common errors
    var strMsg3 = I love big elbows;       // If an error is reported and quotation marks are not used, it will be considered as js code, but js does not have these syntax
    

    Because the attributes in HTML tags use double quotation marks, we prefer to use single quotation marks in JS.

    1. String quote nesting

      JS can nest double quotation marks with single quotation marks, or nest single quotation marks with double quotation marks (outer double inner single, outer single inner double)

      var strMsg = 'I am"Gao Shuaifu"Cheng xuape';   // You can include '' with ''
      var strMsg2 = "I am'Gao Shuaifu'Cheng xuape";  // You can also include '' with ''
      //  Common errors
      var badQuotes = 'What on earth?"; // An error is reported. Single and double quotation marks are not allowed
      
    2. String escape character

      Similar to the special characters in HTML, there are also special characters in the string, which we call escape characters.

      Escape characters start with \. Common escape characters and their descriptions are as follows:

      Escape characterinterpretative statement
      \nNewline, n means newline
      \ \Slash\
      '’Single quotation mark
      "”Double quotation mark
      \ttab indent
      \bb means blank
    3. String length

      A string is composed of several characters. The number of these characters is the length of the string. The length of the entire string can be obtained through the length property of the string.

      var strMsg = "I'm a handsome and golden program ape!";
      alert(strMsg.length); // Display 11
      
    4. String splicing

      • Multiple strings can be spliced with + in the form of string + any type = new string after splicing

      • Before splicing, any type added to the string will be converted into a string, and then spliced into a new string

        //1.1 string "addition"
        alert('hello' + ' ' + 'world'); // hello world
        //1.2 numeric string "addition"
        alert('100' + '100'); // 100100
        //1.3 numeric string + numeric
        alert('11' + 12);     // 1112 
        
        • +No. summary formula: add values and connect characters
    5. String splicing enhancement

      console.log('pink teacher' + 18);        // As long as there are characters, they will be connected 
      var age = 18;
      console.log('pink teacher age Years old');      // That won't work
      console.log('pink teacher' + age);         // Mr. pink 18
      console.log('pink teacher' + age + 'Years old'); // Mr. pink is 18 years old
      
      • Strings and variables are often spliced. Variables can easily modify their values
      • Variables cannot be quoted because quoted variables will become strings
      • If there is string splicing on both sides of the variable, the formula "quote, add", delete the number, and write the variable in the middle
  • Boolean

    Boolean types have two values: true and false, where true represents true (true) and false represents false (false).

    When Boolean and numeric types are added, the value of true is 1 and the value of false is 0.

    console.log(true + 1);  // 2
    console.log(false + 1); // 1
    
  • Undefined and Null

    A variable that has not been assigned a value after declaration will have a default value of undefined (pay attention to the result when connecting or adding)

    var variable;
    console.log(variable);           // undefined
    console.log('Hello' + variable);  // Hello, undefined
    console.log(11 + variable);     // NaN
    console.log(true + variable);   //  NaN
    

    A declared variable is given a null value, and the stored value is null (we continue to study null when learning objects)

    var vari = null;
    console.log('Hello' + vari);  // Hello, null
    console.log(11 + vari);     // 11
    console.log(true + vari);   //  1
    

8.3 obtaining variable data types

  • Gets the data type of the detection variable

    typeof can be used to get the data type of the detection variable

    var num = 18;
    console.log(typeof num) // Result number      
    
  • Literal

    Literal quantity is the representation of a fixed value in the source code. Generally speaking, literal quantity represents how to express this value.

    • Number literal: 8, 9, 10
    • String literal: 'dark horse programmer', 'big front end'
    • Boolean literal: true, false

8.4 data type conversion

What is data type conversion?

The data obtained by using the form and prompt is of string type by default. At this time, you can't simply add directly, but you need to convert the data type of the variable. Generally speaking, it is to convert a variable of one data type into another data type. There are usually three ways to convert:

Convert to string type
 Convert to numeric
 Convert to Boolean
  • Convert to string

    • toString() and String() are used differently.
    • There are three conversion methods, and the third plus sign splicing string conversion method is also called implicit conversion.
  • Convert to digital (key)

    • Pay attention to the case of parseInt and parseFloat words, which are the key points
    • Implicit conversion is that JS automatically converts data types when we perform arithmetic operations
  • Convert to Boolean

    • Values representing null and negative will be converted to false, such as' ', 0, NaN, null and undefined

    • The remaining values are converted to true

      console.log(Boolean('')); // false
      console.log(Boolean(0)); // false
      console.log(Boolean(NaN)); // false
      console.log(Boolean(null)); // false
      console.log(Boolean(undefined)); // false
      console.log(Boolean('Xiaobai')); // true
      console.log(Boolean(12)); // true
      

9 - interpreted and compiled languages

9.1 general

The computer cannot directly understand any language other than machine language, so the program language written by the programmer must be translated into machine language to execute the program. The tool for translating program language into machine language is called translator.
  • There are two ways for translators to translate: one is compilation, the other is interpretation. The difference between the two methods lies in the different time points of translation
  • The compiler compiles before code execution to generate intermediate code files
  • The interpreter is interpreted in time and executed immediately at run time (when the compiler runs in interpretation mode, it is also called the interpreter)

9.2 execution process

It is similar to a dinner party:

	Compile language: first make all the dishes well before you can eat at the table

	Explanation language: it's like eating hot pot, rinsing while eating, and doing it at the same time

10 - keywords and reserved words

10.1 identifier

identification(zhi)Character: refers to the name given by the developer for variables, attributes, functions and parameters.

Identifiers cannot be keywords or reserved words.

10.2 keywords

Keyword: refers to JS Words that have been used by themselves can no longer be used as variable names and method names.

include: break,case,catch,continue,default,delete,do,else,finally,for,function,if,in,instanceof,new,return,switch,this,throw,try,typeof,var,void,while,with Wait.

10.3 reserved words

Reserved words: actually, they are reserved "Keywords", which means that although they are not keywords now, they may become keywords in the future. Similarly, they cannot be used as variable names or method names.

include: boolean,byte,char,class,const,debugger,double,enum,export,extends,fimal,float,goto,implements,import,int,interface,long,mative,package,private,protected,public,short,static,super,synchronized,throws,transient,volatile Wait.

Note: if a reserved word is used as a variable name or function name, it is likely that no error message will be received unless the reserved word is implemented in a future browser. When the browser implements it, the word will be regarded as a keyword, so a keyword error will appear.

JavaScript Foundation Day 02

1 - Operator (operator)

1.1 classification of operators

Operator, also known as operator, is a symbol used to realize the functions of assignment, comparison and arithmetic operation.

JavaScript Operators commonly used in are:
- Arithmetic operator 
- Increment and decrement operators
- Comparison operator
- Logical operator
- Assignment Operators 

1.2 arithmetic operators

  • Overview of arithmetic operators

    Concept: the symbol used in arithmetic operation, which is used to perform the arithmetic operation of two variables or values.

  • Precision of floating point numbers

    The highest precision of floating-point values is 17 decimal places, but it is far less accurate than integers in arithmetic calculations.

    var result = 0.1 + 0.2;//The result is: 0.300000000000000 4
    console.log(0.07 * 100);//The result is: 7.000000000000001
    

    So: do not directly judge whether two floating-point numbers are equal!

  • Expressions and return values

    Expression: it is a combination of numbers, operators, variables, etc. with meaningful arrangement methods that can obtain numerical values

    Simple understanding: it is a formula composed of numbers, operators, variables, etc

    The final result of the expression will be returned to the developer, which is called the return value

1.3 increment and decrement operators

  • Overview of increment and decrement operators

    If you need to add or subtract 1 from a numeric variable repeatedly, you can use the increment (+) and decrement (–) operators.

      	stay JavaScript Medium, increasing(++)And decreasing( -- )It can be placed either before or after the variable. When placed in front of a variable, we can call it a pre increment (decrement) operator, and when placed behind a variable, we can call it a post increment (decrement) operator.
    
      	Note: increment and decrement operators must be used with variables. 
    
  • Increment operator

    • Pre increment operator

      ++The increment before num is self adding 1, which is similar to num = num + 1

      Use the formula: add first and then return the value

    var  num = 10;
    alert(++num + 10);   // 21
    
    • Post increment operator

      Num + + Post increment is to add 1, which is similar to num = num + 1

      Use the formula: first return the original value, and then add it by yourself

    var  num = 10;
    alert(10 + num++);  // 20
    

1.4 comparison operators

  • Overview of comparison operators

    Concept: comparison operator (relational operator) is the operator used when comparing two data. After the comparison operation, a Boolean value (true / false) will be returned as the result of the comparison operation.

  • Equal sign comparison

    console.log(18 == '18'); // true
    console.log(18 === '18'); // false
    

1.5 logical operators

  • Overview of logical operators

    Logical operators are operators used for Boolean operations, and their return values are also Boolean values. In the later development, it is often used to judge multiple conditions

  • Logic and&&

    True is returned only when both sides are true, otherwise false is returned

  • Logical or||

    True is returned only when both sides are true, otherwise false is returned

  • Logical non!

    Logical non (!) is also called negation, which is used to take a value opposite to Boolean value. For example, the opposite value of true is false

    var isOk = !true;
    console.log(isOk);  // false
    
  • Short circuit operation (logic interrupt)

    When the expression value on the left of the parent of the logical element can determine the result, the operation on the value of the expression on the right will not continue;

    • Logic and

      Syntax: expression 1 & & expression 2

        - If the value of the first expression is true, expression 2 is returned
      - If the value of the first expression is false, the expression 1 is returned
      
      console.log( 123 && 456 );        // 456
      console.log( 0 && 456 );          // 0
      console.log( 123 && 456&& 789 );  // 789
      ```
      
- Logical or
  
   ​	Syntax: expression 1 || Expression 2
  
       - If the value of the first expression is true, the expression 1 is returned
        - If the value of the first expression is false, expression 2 is returned
     
  ```js
   console.log( 123 || 456 );         //  123
     console.log( 0 ||  456 );          //  456
     console.log( 123 || 456 || 789 );  //  123
     ```

### 1.6 assignment operator

​		Concept: an operator used to assign data to a variable.

![](images\Picture 9.png)

```js
var age = 10;
age += 5;  // Equivalent to age = age + 5;
age -= 5;  // Equivalent to age = age - 5;
age *= 10; // Equivalent to age = age * 10;

1.7 operator priority

  • The logical non priority in unary operators is very high
  • Logical and have higher priority than logical or

2 - process control

2.1 process control concept

In the process of a program execution, the execution order of each code has a direct impact on the result of the program. Many times we need to control the execution order of the code to realize the functions we want to complete.

Simple understanding: process control is to control the execution of code according to a certain structural order

There are three main structures of process control: sequence structure, branch structure and cycle structure

2.2 sequence flow control

2.3 branch process control

  • Branching structure

JS language provides two branch structure statements: if statement and switch statement

  • if statement

    • Grammatical structure
    // If the condition is true, execute the code, otherwise do nothing
    if (Conditional expression) {
        // Code statement executed when the condition is satisfied
    }
    
      Statement can be understood as a behavior. Loop statement and branch statement are typical statements. A program consists of many statements. Generally, it will be divided into statements one by one.
    
  • if else statement (double branch statement)

    • Grammatical structure

      // If the condition is true, execute the code in if, otherwise execute the code in else
      if (Conditional expression) {
          // [if] the condition is true, the code to be executed
      } else {
          // [otherwise] executed code
      }
      
      
    • Execution process

  • if else if statement (multi branch statement)

    • Grammatical structure

      // Suitable for checking multiple conditions.
      if (Conditional expression 1) {
          Statement 1;
      } else if (Conditional expression 2)  {
          Statement 2;
      } else if (Conditional expression 3)  {
         Statement 3;
       ....
      } else {
          // None of the above conditions holds. Execute the code here
      }
      
      
    • Execution logic

2.4 ternary expression

  • Grammatical structure

    Expression 1 ? Expression 2 : Expression 3;
    
  • Implementation ideas

    • If expression 1 is true, the value of expression 2 is returned; if expression 1 is false, the value of expression 3 is returned
    • Simple understanding: it is similar to the abbreviation of if else

2.5 switch branch process control

  • Grammatical structure

Switch (expression){
case value1:
//Code to execute when expression equals value1
break;
case value2:
//Code to execute when expression equals value2
break;
default:
//Code to execute when the expression is not equal to any value
}

- keyword switch The following parentheses can be expressions or values, usually a variable

- keyword case , An expression or value followed by an option, followed by a colon

- switch The value of the expression matches the value in the structure case Compare the values of 

- If there is a match congruence(===) ,Then the case The associated code block is executed and encountered break Stop when, the whole switch End of statement code execution

- If all case If the values of both do not match the values of the expression, the default Code in

  **Note: Execution case If there is no statement inside break,Then proceed to the next step case The statement inside.**

- switch Statement and if else if Differences between statements

- In general, their two statements can be replaced with each other
- switch...case Statements are usually processed case In order to compare the determined value, and if...else...The statement is more flexible and is often used for range judgment(Greater than or equal to a certain range)
- switch The conditional statement of the program is directly executed after the conditional judgment of the statement, which is more efficient. and if...else If a statement has several conditions, you have to judge how many times.
- When there are fewer branches, if... else Statement execution efficiency ratio switch Statement high.
- When there are many branches, switch The execution efficiency of the statement is higher, and the structure is clearer. 



:heartpulse::heartpulse::heartpulse:

```python
print("If the article is useful to you, please like it O(∩_∩)O~")
System.out.println("If the article is useful to you, please like it O(∩_∩)O~");
cout<<"If the article is useful to you, please like it O(∩_∩)O~"<<endl;

💗💗💗

Topics: Javascript Front-end