7: 一个简单的 if-then 语句的例子

作者:Thau!
如果你在即时对话框中键入yes,你将在看到本页
其他部分前收到一个亲切的问候。若敲入别的则
没有。

这里是该语句的核心:


var monkey_love = prompt("Do you love the monkey?","Type yes or no");

if (monkey_love == "yes")

{

  alert("Welcome! I'm so glad you came! Please, read on!");

}
第一行你见过。它唤起一个对话框并将用户的反馈调入
变量
monkey_love中。但第二行就有些不同:它有个条
件,即如果变量
monkey_love等于值"yes" ,则运行花
括号中的语句。若它等于其他值,则不运行。

注意该条件中的两个等于标记,这是人们容易搞混的
地方之一。如果你只用一个标记,实际上是告诉
JavaScript测试是否monkey_love等于 "yes"
幸运的是,多数浏览器在你运行这些语句时会识别
这些错误并警告你。但最好现在开始就注意别犯这
种错误

其他重要的条件是:

(variable_1 > variable_2)  is true if variable_1 is greater than variable_2

(variable_1 < variable_2)  is true if variable_1 is less than variable_2

(variable_2 <= variable_2)  is true if variable_1 is less than or equal to variable_2

(variable_1 != variable_2)  is true if variable_1 does not equal variable_2
有两个方法可使你的条件更合理:

在运行花括号中的语句前如果你想要两件事为“是”,
可这样做:


if ((variable_1 > 18) && (variable_1 < 21)) 

{ 

  document.writeln("variable_1 can vote, but can't drink.");

}
注意这里的两个“&&”在JavaScript中这是“与”的
意思。也注意整个子句有两个部分,
&&须在圆括号中。

若想两件事之一为真,这样做:


if ((variable_1 == "bananas") || (variable_1 == "JavaScript")) 

{ 

  document.writeln("The monkey is happy because it has " +  variable_1);

}
回到if-then 练习中来!
1页:第二天课程简介
2: 变量介绍
3:首个变量例子的程序主体
4: 字符串的魔力
5: 变量练习
6: if-then 子句
7: if-then 语句的例子
8: if-then 练习
9: 链结事件
10: 图片交换
11: 练习 2
12: 复习