JavaScript教程- JavaScript If...Else 语句

发布时间:2018-11-21 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了JavaScript教程- JavaScript If...Else 语句脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。

条件语句

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

JavaScript 中,我们可使用以下条件语句:

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

If 语句

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

语法

if (condition)
  {
 当条件为 true 时执行的代码
  }

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

实例

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

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

x 的结果是:

 

Good day

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


If...else 语句

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

语法

if (condition)
  {
  当条件为 true 时执行的代码
  }
else
  {
  当条件不为 true 时执行的代码
  }


实例

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

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

的结果是:

Good day



If...else if...else 语句

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

语法

if (condition1)
  {
  当条件 1 为 true 时执行的代码
  }
else if (condition2)
  {
 当条件 2 为 true 时执行的代码
  }
else
  {
  当条件 1 和 条件 2 都不为 true 时执行的代码
  }


实例

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

if (time<10)
  {
  x="Good morning";
  }
else if (time>=10 && time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }

的结果是:

Good day


脚本宝典总结

以上是脚本宝典为你收集整理的JavaScript教程- JavaScript If...Else 语句全部内容,希望文章能够帮你解决JavaScript教程- JavaScript If...Else 语句所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: