JS中if判断 非空即为真 非0即为真

1、字符串参与判断时:非空即为真
判断字符串为空的方法
if(str!=null && str!=undefined && str !=‘‘)
可简写为
if(!str){
    console.log(str)
}
2、数字参与if判断:非0即为真
var i = 0;
if(i){
alert(‘here‘);
}else{
alert(‘test is ok!‘);
} 输出结果为here
var i = 0;
if(i){
alert(‘here‘);
}else{
alert(‘test is ok!‘);
} 输出结果为test is ok

3、在javascript中,哪些值能作为if的条件呢

1、布尔变量true/false
2、数字非0,非NaN/ (0 或NaN)

见下面的例子,莫以为负数就以为if语句为假了。

代码如下: var i = -1;

if(i){

 alert(‘here‘);

}else{

 alert(‘test is ok!‘);

}输出结果为here

3、对象非null/(null或undefined) 
4、字符串非空串(“”)/空串("")

综上所述,对于字符串,不用写一大堆if(str!=null && str!=undefined && str !=‘‘), 只要用一句

if(!str){

    //do something

}

就可以了。

对于数字的非空判断,则要考虑使用isNaN()函数,NaN不和任何类型数据相等,包括它本身,只能用isNaN()判断。对于数字类型,if(a)语句中的a为0时if(a)为假,非0时if(a)为真:

var b;

var a = 0;

a = a + b;

if(a){

 alert(‘1‘);

}else{

 alert(‘2‘);

}

if(isNaN(a)){

 alert(‘a is NaN‘);

}

相关文章