考试首页 | 考试用书 | 培训课程 | 模拟考场 | 考试论坛  
  当前位置:设计制作 > JavaScript > 文章内容
  

JavaScript教程:JavaScriptIf...Else语句

 [ 2017年2月2日 ] 【

条件语句

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

在 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"; }

x 的结果是:

Good day

本文纠错】【告诉好友】【打印此文】【返回顶部
将考试网添加到收藏夹 | 每次上网自动访问考试网 | 复制本页地址,传给QQ/MSN上的好友 | 申请链接 | 意见留言 TOP
关于本站  网站声明  广告服务  联系方式  站内导航  考试论坛
Copyright © 2007-2013 中华考试网(Examw.com) All Rights Reserved