1、概念
if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码。
else 语句 如果 if 语句的条件为false,则执行该代码块。
else if 语句 - 检测一个新的条件,如果第一个条件为false。
if/else 语句在指定的条件为 true 时,执行代码块。如果条件为 false,会执行另外一个代码块。
2、使用
执行代码
// if 语句
let a = true
if (a) {
console.log(1)
}
// if、else语句
let num = 13
if (num > 0) {
console.log(2)
} else {
console.log(3)
}
// if、else if、else语句
let age = 3
if (age === 1) {
console.log('张三')
} else if (age === 2) {
console.log('李四')
} else {
console.log('王五')
}
输出结果
3、拓展
(1)0,NAN,null,undefinded,‘’,false在if语句中会强制转化为 false ;
(2)[],{}转为真;
(3)除NaN以外,其他都===全等于本身;
(4)0 == ‘’和false(成立), 0 === ‘’和false(不成立)。
tip:undefined是派生自null,null是一种特殊的object;NaN是一种特殊的number。undefined==null。