Boolean(逻辑)对象用于将非逻辑值转换为逻辑值(true 或者 false)。
实例
-
检查逻辑值
- 检查逻辑对象是 true 还是 false。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<script type="text/javascript">
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 是逻辑的 "+ b1 +"<br />")
document.write("1 是逻辑的 "+ b2 +"<br />")
document.write("空字符串是逻辑的 "+ b3 + "<br />")
document.write("null 是逻辑的 "+ b4+ "<br />")
document.write("NaN 是逻辑的 "+ b5 +"<br />")
document.write("字符串 'false' 是逻辑的 "+ b6 +"<br />")
</script>
</body>
</html>
效果图:
Boolean 对象
您可以将 Boolean 对象理解为一个产生逻辑值的对象包装器。
Boolean(逻辑)对象用于将非逻辑值转换为逻辑值(true 或者 false)。
创建 Boolean 对象
使用关键词 new 来定义 Boolean 对象。下面的代码定义了一个名为 myBoolean 的逻辑对象:
var myBoolean=new Boolean()
注释:如果逻辑对象无初始值或者其值为 0、-0、null、""、false、undefined 或者 NaN,那么对象的值为 false。否则,其值为 true(即使当自变量为字符串 "false" 时)!
下面的所有的代码行均会创建初始值为 false 的 Boolean 对象。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<script type="text/javascript">
var myBoolean=new Boolean();
document.write(myBoolean);
document.write("<br />");
var myBoolean=new Boolean(0);
document.write(myBoolean);
document.write("<br />");
var myBoolean=new Boolean("");
document.write(myBoolean);
document.write("<br />");
var myBoolean=new Boolean(false);
document.write(myBoolean);
document.write("<br />");
var myBoolean=new Boolean(NaN);
document.write(myBoolean);
document.write("<br />");
</script>
</body>
</html>
效果图:
下面的所有的代码行均会创初始值为 true 的 Boolean 对象:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<script type="text/javascript">
var myBoolean=new Boolean(1);
document.write(myBoolean);
document.write("<br />");
var myBoolean=new Boolean(true);
document.write(myBoolean);
document.write("<br />");
var myBoolean=new Boolean("true");
document.write(myBoolean);
document.write("<br />");
var myBoolean=new Boolean("false");
document.write(myBoolean);
document.write("<br />");
var myBoolean=new Boolean("Bill Gates");
document.write(myBoolean);
document.write("<br />");
</script>
</body>
</html>
效果图: