js-条件语句

条件语句用于基于不同的条件来执行不同的动作。

条件语句

通常在写代码时,您总是需要为不同的决定来执行不同的动作。您可以在代码中使用条件语句来完成该任务。 在 JavaScript 中,我们可使用以下条件语句:

  • if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码
  • if...else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码
  • if...else if....else 语句- 使用该语句来选择多个代码块之一来执行
  • switch 语句 - 使用该语句来选择多个代码块之一来执行

If 语句

只有当指定条件为 true 时,该语句才会执行代码。

语法

1
2
3
4
if (_condition_)
{
_    当条件为 true 时执行的代码_
}

请使用小写的if。使用大写字母(IF)会生成 JavaScript 错误!

实例

当时间小于 20:00 时,生成问候 “Good day”:

1
2
3
if (time<20) { x="Good day"; }

`结果是:`

Good day

请注意,在这个语法中,没有 ..else..。您已经告诉浏览器只有在指定条件为 true 时才执行代码。

If…else 语句

请使用 if….else 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。

语法

1
2
3
4
5
6
7
8
if (_condition_)
{
_    当条件为 true 时执行的代码_
}
else
{
_    当条件不为 true 时执行的代码_
}

实例

当时间小于 20:00 时,生成问候 “Good day”,否则生成问候 “Good evening”。

1
if (time<20) { x="Good day"; } else { x="Good evening"; }

的结果是:

Good day

If…else if…else 语句

使用 if….else if…else 语句来选择多个代码块之一来执行。

语法

1
2
3
4
5
6
7
8
9
10
11
12
if (_condition1_)
{
_    当条件 1true 时执行的代码_
}
else if (_condition2_)
{
_    当条件 2true 时执行的代码_
}
else
{
_  当条件 1 和 条件 2 都不为 true 时执行的代码_
}

 

实例

如果时间小于 10:00,则生成问候 “Good morning”,如果时间大于 10:00 小于 20:00,则生成问候 “Good day”,否则生成问候 “Good evening”:

1
2
3
if (time<10) { document.write("<b>早上好</b>"); } 
else if (time>=10 && time<16) { document.write("<b>今天好</b>"); }
else { document.write("<b>晚上好!</b>"); }

的结果是:

晚上好!

  • 版权声明: 本博客所有文章,未经许可,任何单位及个人不得做营利性使用!转载请标明出处!如有侵权请联系作者。
  • Copyrights © 2015-2023 翟天野

请我喝杯咖啡吧~