在 JavaScript 中,if语句、else if语句 和 else 语句 可以进行任意的嵌套。
if (condition) {
if (condition1){
// do something1
}else if (condition2){
// do something2
}
}else{
if (condition3){
// do something3
}else if (condition4){
// do something4
}else{
// do something5
}
}
JavaScript 的 if 语句、else if 语句和 else 语句可以进行任意的嵌套。
if 语句里面可以嵌套任意的 if、else if 以及 else
<!DOCTYPE html>
<html>
<head>
<title>JavaScript if else 嵌套</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
var a = 10;
if (a > 5){
if (a > 20){
console.log("a > 20");
}else if(a > 10){
console.log("a > 10");
}else{
console.log("a > 5");
}
}else {
console.log("a <= 5");
}
console.log("Over");
</script>
</head>
</html>
程序运行后,控制台输出如下:
首先,我们定义了一个 变量 a,并赋值为 10。接着,我们使用 if 语句判断 a > 5 的条件,如果条件满足,则继续执行判断 a > 20,如果不满足则继续执行 a > 10 的判断,如果最后还是不满足,则会执行 if 里面嵌套的 else 语句。
如果第一个 if 语句都不满足,则会执行执行最外层的 else 语句。最后,我们的程序输出了 "a > 5"
和 "Over"
。
else if 语句里面可以嵌套任意的 if、else if以及else
<!DOCTYPE html>
<html>
<head>
<title>JavaScript if else 嵌套</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
var a = 10;
if (a > 20){
console.log("a > 20")
}else if(a >= 10){
if (a > 15){
console.log("a > 15");
}else if(a > 10){
console.log("a > 10");
}else{
console.log("a >= 10");
}
}else{
console.log("a < 10")
}
console.log("Over");
</script>
</head>
</html>
程序运行后,控制台输出如下:
首先,我们定义了一个变量 a,并赋值为 10。接着,我们使用 if 语句判断 a > 20 的条件,如果条件不满足,则继续执行else if 的判断 a >= 10,如果满足则继续执行 a > 15 的判断和 a > 10的判断,如果最后还是不满足,则会执行 if 里面嵌套的 else 语句。
如果第一个 if 语句都不满足,则会执行执行最外层的 else 语句。最后,我们的程序输出了 "a >= 10"
和 "Over"
。
else 语句里面可以嵌套任意的 if、else if以及else
<!DOCTYPE html>
<html>
<head>
<title>JavaScript if else 嵌套</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
var a = 10;
if (a > 20){
console.log("a > 20")
}else if(a > 15){
console.log("a > 15");
}else{
if (a >= 10){
console.log("a >= 10")
}else{
console.log("a < 10")
}
}
console.log("Over");
</script>
</head>
</html>
程序运行后,控制台输出如下:
首先,我们定义了一个变量 a,并赋值为 10。接着,我们使用 if 语句判断 a > 20 的条件,如果条件不满足,则继续执行else if 的判断 a >= 15,如果条件不满足则继续执行 else 里面嵌套的 if 和 else 的判断。
最后,我们的程序输出了 "a >= 10"
和 "Over"
。
在 JavaScript 中,if 语句、else if 语句 和 else 语句可以进行任意的嵌套。