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" 時)!