html5text非空,一、JS中if判断 非空即为真 非0即为真

痛定思痛。 2022-10-07 04:46 274阅读 0赞

1、字符串参与判断时:非空即为真

判断字符串为空的方法

if(str!=null && str!=undefined && str !=’’)

可简写为

if(!str){

console.log(str)

}

2、数字参与if判断:非0非NAN即为真

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、null类型参与判断

var i =null;

if (i){

alert(“1”)

}else{

alert(“2”)

}输出结果为2

4、undefined类型参与判断

var i;

if (i){

alert(“1”)

}else{

alert(“2”)

}输出结果为2

总结:数字参与判断时非0即为真,字符串参与判断时非空即为真,对象参与判断时非null非undefined即为真({}也为真)

5、在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’);

}

发表评论

表情:
评论列表 (有 0 条评论,274人围观)

还没有评论,来说两句吧...

相关阅读