JavaScript if / else条件

An if statement is used to make the program take a route, or another, depending on the result of an expression evaluation.

根据表达式求值的结果,使用if语句使程序采用一条路线或另一条路线。

This is the simplest example, which always executes:

这是最简单的示例,始终执行:

if (true) {
  //do something
}

on the contrary, this is never executed:

相反,这永远不会执行:

if (false) {
  //do something (? never ?)
}

If you have a single statement to execute after the conditionals, you can omit the block, and just write the statement:

如果您在条件语句之后要执行一条语句,则可以省略该块,而只需编写以下语句:

if (true) doSomething()

The conditional checks the expression you pass to it for true or false value. If you pass a number, that always evaluates to true unless it’s 0. If you pass a string, it always evaluates to true unless it’s an empty string. Those are general rules of casting types to a boolean.

条件检查您传递给它的表达式的真值或假值。 如果传递一个数字,除非它为0,否则始终为true。如果传递一个字符串,则除非它为一个空字符串,否则始终为true。 这些是将类型强制转换为布尔值的一般规则。

其他 (Else)

You can provide a second part to the if statement: else.

您可以为if语句提供第二部分: else

You attach a statement that is going to be executed if the if condition is false:

如果if条件为false,则附加将要执行的语句:

if (true) {
  //do something
} else {
  //do something else
}

Since else accepts a statement, you can nest another if/else statement inside it:

由于else接受一个语句,因此可以在其中嵌套另一个if / else语句:

if (a === true) {
  //do something
} else if (b === true) {
  //do something else
} else {
  //fallback
}

翻译自: https://flaviocopes.com/javascript-if/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值