Boolean(布尔对象)的属性和使用

Boolean 对象

Boolean 对象表示两个值:"true" 或 "false"。

创建 Boolean 对象的语法:

new Boolean(value);	//构造函数
Boolean(value);		//转换函数

参数

参数 value 由布尔对象存放的值或者要转换成布尔值的值。

返回值

当作为一个构造函数(带有运算符 new)调用时,Boolean() 将把它的参数转换成一个布尔值,并且返回一个包含该值的 Boolean 对象。

如果作为一个函数(不带有运算符 new)调用时,Boolean() 只将把它的参数转换成一个原始的布尔值,并且返回这个值。

注释:如果省略 value 参数,或者设置为 0、-0、null、""、false、undefined 或 NaN,则该对象设置为 false。否则设置为 true(即使 value 参数是字符串 "false")。

Boolean 对象属性

属性 描述
constructor 返回对创建此对象的 Boolean 函数的引用
prototype 使您有能力向对象添加属性和方法。

 constructor

<html>
<body>
<script type="text/javascript">
var test=new Boolean();
if(test.constructor==Boolean){
document.write("this is a Boolean");
}
</script>
</body>
</html>
运行结果:this is a Boolean

 prototype

<html>
<body>
<script type="text/javascript">
function student(id,name,age){
this.id=id;
this.name=name;
this.age=age;}
var stu=new student("17101","Amily",17) ;
student.prototype.sex=null;
stu.sex="男";
document.write(stu.sex);
</script>
</body>
</html>
运行结果:男

Boolean 对象方法

方法 描述
toSource() 返回该对象的源代码。
toString() 把逻辑值转换为字符串,并返回结果。
valueOf() 返回 Boolean 对象的原始值。

toSource

<html>
<body>
<script type="text/javascript">
function student(id,name,age){
this.id=id;
this.name=name;
this.age=age;}
var stu=new student("17101","Amily",17) ;

document.write(stu.toSource);
</script>
</body>
</html>
运行结果:({id:"17101",name:"Amily",age:17})

toString

<html>
<body>
<script type="text/javascript">
var status=new Boolean(false)
document.write(status)
</script>
</body>
</html>
运行结果:false

toValueof()

<html>
<body>
<script type="text/javascript">
var status=new Boolean(false)
document.write(status.valueOf())
</script>
</body>
</html>
运行结果:false

&&和||

Boolean类型,处理0,NaN,undefine,false, null表示false,其余表示true

猜你喜欢

转载自blog.csdn.net/wwwkm123/article/details/111028990