美文网首页
JS--判断条件

JS--判断条件

作者: nickName0 | 来源:发表于2017-11-20 22:56 被阅读86次
  • JS--判断条件
    JavaScript使用if () { ... } else { ... }来进行条件判断:
var index = 12;
if (index > 10) {
    console.log('index > 10');
}else {
    console.log('index <= 10');
}

其中else语句是可选的。如果语句块只包含一条语句,那么可以省略{}

if (index > 10)
    console.log('index > 10');
else
    console.log('index <= 10');

省略{}的危险之处在于,如果后来想添加一些语句,却忘了写{},就改变了if...else...的语义,例如:

if (index > 10)
    console.log('index > 10');
else
    console.log('index <= 10');
    console.log('index <= 10'); // 这行代码每次都会执行,它不属于else的范畴之内;建议使用if else语句不要省略{}
  • 多行条件判断
    过个if else 嵌套使用和iOS一样;
    在多个if...else...语句中,如果某个条件成立,则后续就不再继续判断了,例如以下例子只会输出index > 10,不会输出index == 12
var index = 12;
if (index > 10) {
    console.log('index > 10');
}else if ( index == 12) {
    console.log('index = 12');
}else {
    console.log('index < 12');
}

注意:JavaScript把null、undefined、0、NaN和空字符串''视为false,其他值一概视为true

相关文章

网友评论

      本文标题:JS--判断条件

      本文链接:https://www.haomeiwen.com/subject/tlwbvxtx.html