Difference 1022 switch branch flow control, and if else if statement

2.5.1 grammatical structure, the implementation of ideas, Notes

switch statement is a multi-branch statement, which is used to execute different code based on different conditions. When you want a range of options for a particular value for the variable is set, you can use the switch.

switch( 表达式 ){ 
    case value1:
        // 表达式 等于 value1 时要执行的代码
        break;
    case value2:
        // 表达式 等于 value2 时要执行的代码
        break;
    default:
        // 表达式 不等于任何一个 value 时要执行的代码
}
  • switch: switching, case: small example Options

  • Within parentheses after the keyword switch may be an expression or a value , usually a variable .

  • Keyword case, followed by an expression or the value of an option, followed by a colon.

  • Compared with the value of the case will be of value in the structure of the switch expression.

  • If there is a match congruent (===) , it is associated with the case code block is executed, and stops when it encounters BREAK, the entire switch statement code execution ends.

  • If all values ​​are case and the value of the expression does not match, default in the code is executed.

    Note: When you perform inside the case statement, if not break, then continue to the next statement is executed inside a case. [Break: exit the switch statement. ]

The difference between 2.5.2 switch statement and if else if statement

  • In general, they can replace each two statements
  • switch ... case statement case the comparison process typically determined value, and if ... else ... statement is more flexible, commonly used in the determination range (greater than, equal to a certain range)
  • Directly to the execution program makes a conditional judgment after the switch statement conditional statement, more efficient. And if ... else statement there are several conditions, you have to determine how many times.
  • When the branch relatively little time, if ... else statement execution efficiency is higher than the switch statement.
  • When the branch relatively long time, the efficiency of the switch statement is relatively high, and the structure more clearly.
        demo:查询水果案例
        // 弹出 prompt 输入框,让用户输入水果名称,把这个值取过来保存到变量中。
        // 将这个变量作为 switch 括号里面的表达式。
        // case 后面的值写几个不同的水果名称,注意一定要加引号 ,因为必须是全等匹配。
        // 弹出不同价格即可。同样注意每个 case 之后加上 break ,以便退出 switch 语句。
        // 将 default 设置为没有此水果。
        var fruit = prompt('请您输入查询的水果:');
        switch (fruit) {
            case '苹果':
                alert('苹果的价格是 3.5/斤');
                break;
            case '榴莲':
                alert('榴莲的价格是 35/斤');
                break;
            default:
                alert('没有此水果');
        }

Guess you like

Origin www.cnblogs.com/jianjie/p/12134558.html