微信扫一扫打赏支持

范仁义js课程---22、选择结构(if)

范仁义js课程---22、选择结构(if)

一、总结

一句话总结:

在js中,可以用if语句实现选择结构,有单分支(只有if)、双分支(if,else)、多分支(有if、else-if、else)

 

1、单分支的if选择结构?

if(条件语句){ 语句块1 }:当条件为 true 时,执行 语句块1。
当时间小于 20:00 时,生成问候 "Good day"if (time<20)
{
    x="Good day";
}

 

 

2、双分支的if选择结构?

if(条件语句){ 语句块1 }else{ 语句块2 }:当条件为 true 时,执行 语句块1,否则执行 语句块2。
当时间小于 20:00 时,生成问候 "Good day",否则生成问候 "Good evening"if (time<20)
{
    x="Good day";
}
else
{
    x="Good evening";
}

 

 

3、多分支的if选择结构?

if(条件1){ 语句块1 }else if(条件2){ 语句块2 }else{ 语句块3 }:当条件1为 true 时,执行 语句块1,当条件1不成立且条件2成立的时候,执行 语句块2,否则执行 语句块3
如果时间小于 10:00,则生成问候 "Good morning",如果时间大于 10:00 小于 20:00,则生成问候 "Good day",否则生成问候 "Good evening"if (time<10)
{
    document.write("<b>早上好</b>");
}
else if (time>=10 && time<16)
{
    document.write("<b>今天好</b>");
}
else
{
    document.write("<b>晚上好!</b>");
}

 

 

 

二、选择结构(if)

博客对应课程的视频位置:22、选择结构(if)
https://www.fanrenyi.com/video/19/118

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>选择结构(if)</title>
 6 </head>
 7 <body>
 8 <!--
 9 if
10 
11 switch
12 
13 
14 推荐在写if语句的时候,就算只有一条语句,也把大括号带上,这样不容易出错
15 
16 单分支
17 if(条件){ 语句 }
18 
19 双分支的情况
20 if(条件){ 语句1 }
21 else{ 语句2 }
22 
23 多分支
24 if(条件1){ 语句1 }
25 else if(条件2){ 语句2 }
26 else{ 语句3 }
27 
28 
29 -->
30 <script>
31     // var isRain=false;
32     // if(isRain){
33     //     alert('出去');
34     //     alert('愉快的玩耍');
35     // }else{
36     //     alert('不出去');
37     //     alert('在家玩耍');
38     // }
39 
40     // var zhongjiang=true;
41     // if(zhongjiang){
42     //     console.log('我们就愉快的玩耍吧');
43     // }
44     // if(zhongjiang)
45     // {
46     //     console.log('我们就愉快的玩耍吧');
47     //     console.log('123');
48     // }
49 
50     // var a=30;
51     // if(a>5&&a<20){
52     //     console.log('a>5&&a<20');
53     // }
54 
55     var score=100;
56     // if(score>=100){
57     //     alert('奖励一辆航空母舰');
58     // }
59     // if(score>=80&&score<100){
60     //     alert('奖励一辆奔驰');
61     // }
62     // if(score>=60&&score<80){
63     //     alert('奖励一本参考手册');
64     // }
65     // if(score<60){
66     //     alert('奖励一顿竹笋炒肉');
67     // }
68 
69     // if(score>=100){
70     //     alert('奖励一辆航空母舰');
71     // }else if(score>=80){
72     //     alert('奖励一辆奔驰');
73     // }else if(score>=60){
74     //     alert('奖励一本参考手册');
75     // }else{
76     //     alert('奖励一顿竹笋炒肉');
77     // }
78 
79     // if(score>=100){
80     //     alert('奖励一辆航空母舰');
81     // }
82     // if(score>=80){
83     //     alert('奖励一辆奔驰');
84     // }
85     // if(score>=60){
86     //     alert('奖励一本参考手册');
87     // }
88     // if(score<60){
89     //     alert('奖励一顿竹笋炒肉');
90     // }
91 
92 </script>
93 </body>
94 </html>

 

 

 

 
posted @ 2020-02-27 21:15  范仁义  阅读(322)  评论(0编辑  收藏  举报