2, Select structure

Keywords: Javascript Front-end ECMAScript html

catalogue

1. Composition of JavaScript

1. Three cores

2. Common methods of window objects

2.if selection structure

3. Multiple if selection structure

4. Nested if selection structure

5.switch selection structure

6. Ternary expression

1. Composition of JavaScript

1. Three cores

  1. ESMAScript core syntax (Standard Specification) - > ES6
  2. The BOM browser object mode is actually a window object that can operate the browser
  3. DOM document object model is actually a document object, which can operate all elements in a web page

2. Common methods of window objects

1.alert() method, which is used to open the message box

2.prompt() method, which is used to open the input box. The type of data returned by the input box is string

3. The confirm () method is used to open the OK box. There are two buttons in the confirmation box, OK and cancel. Click OK to return true, and click Cancel to return false

4.parseInt() method, which is used to forcibly convert string data to integer

5.parseFloat() method, which is used to forcibly convert string data to floating-point type

6.isNaN() method, used to judge whether a piece of data is NaN data (not a number

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>window Common methods of object</title>
</head>
<body>
    <script>
        // window object is the built-in object of js, which is used to operate BOM. It provides many methods to operate the browser.
        // console.log(window);

        // Bullet frame method:
        // alert() method to open the message box
        // window.alert('Hello ')
        // prompt() method, which is used to open the input box. This method will return the input result of type string
        // var name = window.prompt('Please enter name: ')
        // console.log(name);
        // The confirm() method is used to open the confirmation box. The return value of this method is of boolean type
        // var isok = window.confirm('are you sure to break up? ')
        // console.log(isok);

        // Type conversion method:
        var str1 = '100.55'
        console.log(typeof str1);
        // parseInt() method to force a string to an integer
        // Note: the window object is the default object of the browser, so it can be omitted in actual use
        var num1 = parseInt(str1)
        console.log(str1);
        console.log(num1);
        console.log(typeof num1);
        // parseFloat() method to force a string to float
        var num2 = parseFloat(str1)
        console.log(num2);
        console.log(typeof num2);
        // isNaN() method, used to judge whether a piece of data is NaN data (not a number)
        // It is to judge whether a data is a number, whether a number returns true or false.
        var str2 = '100'
        var str3 = '100.55'
        var str4 = 'How do you do'
        console.log(isNaN(str2));
        console.log(isNaN(str3));
        console.log(isNaN(str4));
    </script>
</body>
</html>

The console displays:

2.if selection structure

The syntax of the if selection structure is: if (judgment condition) {code block executed after the condition is met}

If else selection structure, the condition in if() holds, execute the code block in if {}, otherwise execute the code block in else {}

Note: when there are only conditional statements in if or else, you can omit {}

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>if Select structure</title>
</head>
<body>
    <script>
        // If you score more than 80 points, you will get 400 yuan
        var score = 20
        // if() writes the condition, the condition returns true, and executes the code in {}
        if(score>=80){
            console.log('Get 400 yuan');
        }
        console.log('----------------------------');
        // If the score is more than 60 points, you will get 200 yuan, otherwise you will be fined 50 times
        if(score>=60){
            console.log('Get 200 yuan');
        }else{
            // else statements must be used in conjunction with if statements and cannot be used alone.
            // When the if does not hold, execute the else statement.
            console.log('Penalty copy 50 times');
        }
        console.log('----------------------------');
        // When the code blocks of if and else have only one statement, {} can be omitted
        if(score>=70)
            console.log('Reward 100 yuan');
        else 
            console.log('Penalty copy 50 times');
    </script>
</body>
</html>

The console displays:

3. Multiple if selection structure

In the multiple if selection structure, if one of the conditions is satisfied, execute the code corresponding to the condition, and jump out of the whole program structure after execution.

If all the conditions are not true, else is executed if there is else; without else, the whole program structure ends.

Exercise:

If there are 50 million, buy a house in Beijing

If there are 30 million, buy a house in Shanghai

If there are 10 million, buy a house in Shenzhen

If there are 8 million, buy a house in Guangzhou

If there are 3 million, buy a house in Nanjing

Otherwise, don't buy a house

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>multiple if Select structure</title>
</head>

<body>
    <script>
        /* 
            If there are 50 million, buy a house in Beijing
            If there are 30 million, buy a house in Shanghai
            If there are 10 million, buy a house in Shenzhen
            If there are 8 million, buy a house in Guangzhou
            If there are 3 million, buy a house in Nanjing
            Otherwise, don't buy a house
        */
        // In the multiple if selection structure, if one of the conditions is satisfied, execute the code corresponding to the condition, and jump out of the whole program structure after execution.
        // Therefore, when using the multiple if selection structure, it is judged that the number is larger than the number to be compared first and smaller than the number to be compared first.
        var money = parseInt(prompt('Please enter your deposit(Company:ten thousand)'))
        if (money >= 5000) {
            alert('Buy a house in Beijing')
        } else if (money >= 3000) {
            alert('Buy a house in Shanghai')
        } else if (money >= 1000) {
            alert('Buy a house in Shenzhen')
        } else if (money >= 800) {
            alert('Buy a house in Guangzhou')
        } else if (money >= 300) {
            alert('Buy a house in Nanjing')
        } else {
            alert('Otherwise, don't buy a house')
        }
    </script>
</body>

</html>

The pop-up box is displayed as:

 

4. Nested if selection structure

Nested if selection structure: continue to use if structure statements in a complete if or else structure.

Exercise:

Please enter whether you are a member, y is a member and n is not a member

Please enter consumption amount

Members: 20% off for consumption and 60% off for 100 yuan

Non members: 10% off for consumption over 200 yuan, no discount for consumption less than 200 yuan

Finally, output the actual consumption amount this time

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>nesting if Select structure</title>
</head>
<body>
    <script>
        // Nested if selection structure: continue to use if structure statements in a complete if or else structure.
        /* 
            Exercise:
            Please enter whether you are a member, y is a member and n is not a member
            Please enter consumption amount
            Members: 20% off for consumption and 60% off for 100 yuan
            Non members: 10% off for consumption over 200 yuan, no discount for consumption less than 200 yuan
            Finally, output the actual consumption amount this time
        */
        var ishy = prompt('Are you a member(y/n):')
        var money = parseFloat(prompt('Please enter consumption amount:'))
        // The first level if is to judge whether it is a member
        if(ishy=='y'){
            // The second level if is to judge the consumption amount
            //Give a 60% discount when the consumption amount reaches 100
            if(money>=100){
                money *= 0.6   //money = money * 0.6
            }else{
                money *= 0.8
            }
        }else{
            //For non members, 10% off for consumption over 200
            if(money>=200){
                money *= 0.9
            }
        }

        alert('Consumption amount of this shopping:'+money)
    </script>
</body>
</html>

The pop-up box is displayed as:

 

 

Comprehensive exercises for multiple if and nested if:

Enter the month and year and output the number of days in the month?

Leap year formula: a year can be divided by 4, but not by 100; or a year can be divided by 400. February of a leap year is 29 days and February of a normal year is 28 days.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>multiple if And nesting if Comprehensive practice of</title>
</head>
<body>
    <script>
        /* 
        Enter the month and year and output the number of days in the month?
        Leap year formula: a year can be divided by 4, but not by 100; or a year can be divided by 400. February of a leap year is 29 days and February of a normal year is 28 days.
        */
        var year = parseInt(prompt('Please enter the year:'))
        var month = parseInt(prompt('Please enter month:'))
        var days = 0;  //Save days
        if(month===1 || month===3 || month===5 || month===7 || month===8 || month===10 || month===12){
            days = 31
        }else if(month===4 || month===6 || month===9 || month===11){
            days = 30
        }else{
            // February, the year needs to be judged
            if(year%4===0 && year%100!=0 || year%400===0){
                days = 29
            }else{
                days = 28
            }
        }
        // The + sign here is used for string splicing
        alert(year+'year'+month+'Month, yes'+days+'day')
    </script>
</body>
</html>

The pop-up box is displayed as:

 

 

5.switch selection structure

switch selection structure is also used for multi branch judgment. The syntax structure is simpler than multiple if.

However, the switch selection structure can only make equivalence judgment.

The syntax structure is: put the variables that need to be judged by equivalence into (). Judge by equivalence with the value after case in {}.

Note 1: before the end of a case statement, a break is usually added to indicate that the switch selection structure jumps out, because,

Switch selects the structure. Once the judgment of the case in the switch is established, the latter case will not be judged again.

Note 2: if the output results of multiple cases are the same, you can combine the results of multiple cases and omit the break of the previous case.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>switch Select structure</title>
</head>

<body>
    <script>
        // The ranking is: 1. Reward the car, 2. Reward the computer, 3. Reward the mobile phone, 4. No reward, otherwise you will be fined
        var mc = 1
        if (mc === 1) {
            console.log('Reward car');
        } else if (mc === 2) {
            console.log('Reward computer');
        } else if (mc === 3) {
            console.log('Reward mobile phone');
        } else if (mc === 4) {
            console.log('No reward');
        } else {
            console.log('Run around the playground 10 times');
        }
        console.log('---------------------------------');
        /* 
            switch Selection structure is also used for multi branch judgment. The syntax structure is simpler than multiple if.
            However, the switch selection structure can only make equivalence judgment.
        */
        // Put the variables to be judged in () and use the case in {} to compare with the variables in () one by one 
        // After one of the cases is satisfied, the code in the case is executed
        // However, be sure to add a break at the bottom of the case statement to jump out of the whole switch
        // Because after one case is satisfied, the other cases will not be judged, but will be executed directly.   
        switch (mc) {
            case 1:
                console.log('Reward car');
                break;
            case 2:
                console.log('Reward computer');
                break;
            case 3:
                console.log('Reward mobile phone');
                break;
            case 4:
                console.log('No reward');
                break;
            default:
                console.log('Penalty code');
                break;
        }
        console.log('-----------------------------');
        //Today's income is the day of the week: a 20% discount for all goods in the 1 3 5 supermarket, a 70% discount for all goods in the 2 4 6 supermarket, and a 50% discount for all goods in the 7
        //If the output results of multiple cases are the same, you can combine the results of multiple cases and omit the break of the previous case
        var week = parseInt(prompt('Please enter the day of the week today:'))
        switch (week) {
            case 1:
            case 3:
            case 5:
                alert('20% off all goods in the supermarket')
                break;  //Jump out of the whole switch
            case 2:
            case 4: 
            case 6: 
                alert('20% off all goods in the supermarket')
                break;
            // When all case s are not valid and there is a default, the default is executed
            default: 
                alert('50% off all goods in the supermarket')
                break;
        }
    </script>
</body>

</html>

The console displays:

The pop-up box is displayed as:

 

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>switch Exercises</title>
</head>

<body>
    <script>
        // Enter the year, month and date, and output the day of the year
        // For example, if the year is 2021, the month is 11 and the date is 9, calculate how many days 2021-11-9 is the first day of the whole year
        // The trick is: write the case backwards without break ing.
        var year = parseInt(prompt('Please enter the year:'))
        var month = parseInt(prompt('Please enter month:'))
        var day = parseInt(prompt('Please enter date:'))
        var sum = 0  //Total number of days to save
        //Use the switch statement to accumulate the days of the whole month
        switch (month - 1) {
            case 12:
                sum += 31
            case 11:
                sum += 30
            case 10:
                sum += 31
            case 9:
                sum += 30
            case 8:
                sum += 31
            case 7:
                sum += 31
            case 6:
                sum += 30
            case 5:
                sum += 31
            case 4:
                sum += 30
            case 3:
                sum += 31
            case 2:
                if (year % 4 === 0 && year % 100 != 0 || year % 400 === 0) {
                    sum += 29
                } else {
                    sum += 28
                }
            case 1:
                sum += 31
        }
        // Plus the number of days in the current month
        sum += day
        alert(year + '-' + month + '-' + day + 'It's the third day of the year' + sum + 'day')
    </script>
</body>

</html>

The pop-up box is displayed as:

 

 

 

6. Ternary expression

Ternary expressions can simplify the basic if else statement structure

var c = a > 10 ? 100 : 200

Ternary expressions can also simplify the structure of complex if else statements

var e = a > 20 ? 200 : (a > 10 ? 100 : 300)
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ternary expression</title>
</head>
<body>
    <script>
        // Ternary expressions can simplify the basic if else statement structure
        var a = 100
        var b = 200
        var c;
        if(a>b){
            c = 300
        }else{
            c = 400
        }
        console.log(c);
        // Ternary expression:? The expression on the left returns true and returns? The result on the right, otherwise: the result on the right.
        var d = a>b ? 300 : 400
        console.log(d);
        console.log('-------------------------');
        // Ternary expressions can also simplify the structure of complex if else statements
        var num = 1
        var sex;
        if(num===1){
            sex='male'
        }else if(num===2){
            sex='female'
        }else {
            sex='unknown'
        }
        console.log(sex);
        var sex2 = num===1 ? 'male' : (num===2 ? 'female' : 'unknown')
        console.log(sex2);
    </script>
</body>
</html>

The console displays:

Posted by jikishlove on Thu, 18 Nov 2021 07:04:12 -0800