美文网首页
JavaScript Boolean 对象

JavaScript Boolean 对象

作者: 深沉的简单 | 来源:发表于2017-04-13 10:39 被阅读8次

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

创建 Boolean 对象的语法:

var test=new Boolean(1);
console.log(test);
var test1=Boolean(1);
console.log(test1);
Paste_Image.png

返回值

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

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

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

Boolean 对象属性

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

constructor 属性返回对创建此对象的 Boolean 函数的引用。

得出创建此对象的构造函数

var test=new Boolean();
console.log(test.constructor==Boolean);//true
var test1=new Array();
console.log(test1.constructor==Array);//true
var test2=new Date();
console.log(test2.constructor==Date);//true
var test3=new String();
console.log(test3.constructor==String);//true

prototype 属性使您有能力向对象添加属性和方法。

Boolean.prototype.s=1;
var test=new Boolean();
console.log(test);
Paste_Image.png

Boolean 对象方法

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

toSource() 方法返回表示对象源代码的字符串。

注释:该方法在 Internet Explorer 中无效。

var test=new Boolean();
console.log(test.toSource());//(new Boolean(false))
var test1="你好";
console.log(test1.toSource());//(new String("\u4F60\u597D"))
var test2=[1,2,3,4];
console.log(test2.toSource());//[1, 2, 3, 4]
var test3={"a":1};
console.log(test3.toSource());//({a:1})

toString() 方法可把一个逻辑值转换为字符串,并返回结果。

//使用 toString() 来把一个布尔值转换成字符串。
var test=new Boolean(1);
console.log(test.toString());//true

valueOf() 方法可返回 Boolean 对象的原始值。

语法

booleanObject.valueOf()
//使用 valueOf() 来取得一个 Boolean 对象的原始值。
var test=new Boolean(1);
console.log(test.valueOf());//true

相关文章

网友评论

      本文标题:JavaScript Boolean 对象

      本文链接:https://www.haomeiwen.com/subject/dnbuattx.html