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
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
}
//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');
}
var a = 0;
a = a + b;
if(a){
alert('1');
}else{
alert('2');
}
if(isNaN(a)){
alert('a is NaN');
}