JS条件语句-if else
时间:2020-02-23 14:33:48 来源:igfitidea点击:
在本教程中,我们将学习JavaScript条件语句If Else。
如果满足某些条件,我们将使用条件语句执行一段代码。
if语句
我们使用if关键字创建一个if语句。
语法:
if ( comparison ) {
//some code goes here...
}
在下面的示例中,我们有一个if语句,如果满足条件,则执行其中的代码。
var x = 10;
console.log("x = " + x);
if ( x > 0 ) {
console.log("x is greater than 0");
}
console.log("End of code");
在上面的代码中,我们创建了一个if语句。
我们将变量x设置为10。
在if语句中,我们正在检查x>0。
这是正确的,因此将执行if块中的代码。
x = 10 x is greater than 0 End of code
if/else语句
我们使用if和else关键字来创建一个if/else语句。
语法:
if ( comparison ) {
//if block code
} else {
//else block code
}
在下面的示例中,我们有一个if语句,如果满足条件,则执行其中的代码。
否则,执行else块。
var x = 10;
console.log("x = " + x);
if ( x > 20 ) {
console.log("x is greater than 20");
} else {
console.log("x is less than 20");
}
console.log("End of code");
在上面的代码中,我们创建了一个if/else语句。
我们将变量x设置为10。
在if语句中,我们正在检查x>20。
这是false,因此执行else块内的代码。
x = 10 x is less than 20 End of code
else if语句
我们可以结合使用" else"和" if"关键字来创建多个if/else语句。
语法:
if ( comparison1 ) {
//if block1 code
} else if ( comparison2 ) {
//if block2 code
} else {
//else block code
}
在下面的示例中,我们有多个if/else语句。
var x = 10;
console.log("x = " + x);
if ( x < 0 ) {
console.log("x is less than 0");
} else if ( x == 0) {
console.log("x is equal to 0");
} else {
console.log("x is greater than 0");
}
console.log("End of code");
在上面的代码中,我们创建了一个if/else语句。
我们将变量x设置为10。
在if语句中,我们正在检查x>20。
这是false,因此执行else块内的代码。
x = 10 x is greater than 0 End of code
if/else嵌套
我们可以在另一个if/else语句中包含if/else语句。
以下是嵌套if/else语句的示例。
var x = 10;
var y = 20;
if ( x > 0 ) {
if ( y > x ) {
console.log("y is greater than x");
} else if ( y == x ) {
console.log("y is equal to x");
} else {
console.log("y is less than x");
}
} else {
console.log("x is not greater than zero");
}
y is greater than x

