条件语句
通常在写代码时,您总是需要为不同的决定来执行不同的动作。您可以在代码中使用条件语句来完成该任务。
在 JavaScript 中,我们可使用以下条件语句:
- if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码
- if...else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码
- JavaScript三目运算 - 当条件为true 时执行代码,当条件为 false 时执行其他代码
- if...else if....else 语句- 使用该语句来选择多个代码块之一来执行
- switch 语句 - 使用该语句来选择多个代码块之一来执行
if...else 判断
if (condition)
{
当条件为 true 时执行的代码
}
else
{
当条件不为 true 时执行的代码
}
实例代码:
function myTest(val) {
if (val < 5) {
return "Less than 5";
} else if (val < 10) {
return "Less than 10";
} else {
return "Greater than or equal to 10";
}
}
myTest(7);
switch 判断
switch(n)
{
case 1:
执行代码块 1
break;
case 2:
执行代码块 2
break;
default:
n 与 case 1 和 case 2 不同时执行的代码
}
实例代码:
function myTest(val) {
var answer = "";
switch (val) {
case 'a':
answer = "apple";
break;
case 'b':
answer = "bird";
break;
case 'c':
answer = "cat";
break;
default:
answer = "stuff";
}
return answer;
}
myTest(1);
ps: 三元云算法:(condition1) ? true-doing : else-doing; 条件为true执行true-doing,否则执行else-doing;
5 > 3 ? alert("5大于3") : alert("5小于3");