Boolean(布爾)對象用於將非布爾值轉換為布爾值(true 或者 false)。
檢查布爾值
檢查布爾對象是 true 還是 false。
源代碼示例:
<!DOCTYPE html> <html> <body> <script> var b1=new Boolean(0); var b2=new Boolean(1); var b3=new Boolean(""); var b4=new Boolean(null); var b5=new Boolean(NaN); var b6=new Boolean("false"); document.write("0 is boolean "+ b1 +"<br>"); document.write("1 is boolean "+ b2 +"<br>"); document.write("An empty string is boolean "+ b3 + "<br>"); document.write("null is boolean "+ b4+ "<br>"); document.write("NaN is boolean "+ b5 +"<br>"); document.write("The string 'false' is boolean "+ b6 +"<br>"); </script> </body> </html>
測試結果:
0 is boolean false 1 is boolean true An empty string is boolean false null is boolean false NaN is boolean false The string 'false' is boolean true
創建 Boolean 對象
Boolean 對象代表兩個值:"true" 或者 "false"
下面的代碼定義了一個名為 myBoolean 的布爾對象:
var myBoolean=new Boolean();
如果布爾對象無初始值或者其值為:
0 -0 null "" false undefined NaN
那麼對象的值為 false。否則,其值為 true(即使當自變量為字符串 "false" 時)!