shenjianxz 2016-02-13
JavaScript 条件语句
条件语句
条件语句用于基于不同的条件来执行不同的动作。
通常在写代码时,您总是需要为不同的决定来执行不同的动作。您可以在代码中使用条件语句来完成该任务。
在 JavaScript 中,我们可使用以下条件语句:
1. if语句
if (condition)
{
当条件为 true 时执行的代码
}
2. if...else语句
if (condition)
{
当条件为 true 时执行的代码
}
else
{
当条件不为 true 时执行的代码
}
3. if...else if...else语句
if (condition1)
{
当条件 1 为 true 时执行的代码
}
else if (condition2)
{
当条件 2 为 true 时执行的代码
}
else
{
当条件 1 和 条件 2 都不为 true 时执行的代码
}
4. switch语句
switch(n)
{
case 1:
执行代码块 1
break;
case 2:
执行代码块 2
break;
default:
n 与 case 1 和 case 2 不同时执行的代码
}
switch语句中的关键字
break
使用 break 来阻止代码自动地向下一个 case 运行。
default
使用 default 关键词来规定匹配不存在时做的事情
var day=new Date().getDay();
switch (day)
{
case 6:
x="Today it's Saturday";
break;
case 0:
x="Today it's Sunday";
break;
default:
x="Looking forward to the Weekend";
}
运行结果:
Today it's Saturday