首頁  >  文章  >  web前端  >  js中各種類型的變數在if條件中是true還是false_javascript技巧

js中各種類型的變數在if條件中是true還是false_javascript技巧

WBOY
WBOY原創
2016-05-16 16:41:541199瀏覽

js的弱型別讓人感覺很多東西都比較迷惑,例如變數在if條件中到底是true還是false,如果在強型別語言中將一個非boolean型別的變數放在if條件中時,是需要進行型別轉換的,但是js不需要,下面來進行測試,測試常見的變數類型在if條件中的表現

!function test1(){ 

<span style="color:#ff0000;">var a,b=-1,c= 1,d= 0,e=null,f=undefined,g='',h="";</span> 
if(!a){ 
console.log('a='+a) 
} 
if(!b){ 
console.log("b="+b) 
} 
if(!c){ 
console.log("c="+c) 
} 
if(!d){ 
console.log("d="+d) 
} 
if(!e){ 
console.log("e="+e) 
} 
if(!f){ 
console.log("f="+f) 
} 
if(!g){ 
console.log("g="+g) 
} 
if(!h){ 
console.log("h="+h) 
} 

}() 

設定了各種變數類型,分別放入if條件中

執行結果
a=undefined
d=0
e=null
f=undefined
g=
h=
i=false

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn