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