Boolean() 构造函数
Boolean()
构造函数创建 Boolean
对象。当作为函数调用时,它返回布尔类型的原始值。
¥The Boolean()
constructor creates Boolean
objects. When called as a function, it returns primitive values of type Boolean.
Try it
语法
¥Syntax
new Boolean(value)
Boolean(value)
注意:
Boolean()
可以与new
一起调用,也可以不与new
一起调用,但效果不同。参见 返回值。¥Note:
Boolean()
can be called with or withoutnew
, but with different effects. See Return value.
参数
返回值
¥Return value
当 Boolean()
作为构造函数(与 new
)被调用时,它会创建一个 Boolean
对象,该对象不是基元。
¥When Boolean()
is called as a constructor (with new
), it creates a Boolean
object, which is not a primitive.
当 Boolean()
作为函数调用时(没有 new
),它将参数强制为布尔原语。
¥When Boolean()
is called as a function (without new
), it coerces the parameter to a boolean primitive.
警告:你应该很少发现自己使用
Boolean
作为构造函数。¥Warning: You should rarely find yourself using
Boolean
as a constructor.
描述
¥Description
作为第一个参数传递的值为 转换为布尔值。如果该值被省略或者是 0
、-0
、0n
、null
、false
、NaN
、undefined
或空字符串 (""
),则该对象的初始值为 false
。所有其他值,包括任何对象、空数组 ([]
) 或字符串 "false"
,都会创建一个初始值为 true
的对象。
¥The value passed as the first parameter is converted to a boolean value. If the value is omitted or is 0
, -0
, 0n
, null
, false
, NaN
, undefined
, or the empty string (""
), then the object has an initial value of false
. All other values, including any object, an empty array ([]
), or the string "false"
, create an object with an initial value of true
.
注意:当非标准属性
document.all
用作此构造函数的参数时,结果是值为false
的Boolean
对象。此属性是遗留的且非标准的,不应使用。¥Note: When the non-standard property
document.all
is used as an argument for this constructor, the result is aBoolean
object with the valuefalse
. This property is legacy and non-standard and should not be used.
示例
创建初始值为 false 的布尔对象
¥Creating Boolean objects with an initial value of false
const bZero = new Boolean(0);
const bNull = new Boolean(null);
const bEmptyString = new Boolean("");
const bfalse = new Boolean(false);
typeof bfalse; // "object"
Boolean(bfalse); // true
请注意,使用 Boolean()
将 Boolean
对象转换为基元总是会产生 true
,即使该对象拥有 false
的值。因此,始终建议你避免构造 Boolean
封装对象。
¥Note how converting a Boolean
object to a primitive with Boolean()
always yields true
, even if the object holds a value of false
. You are therefore always advised to avoid constructing Boolean
wrapper objects.
如果需要从封装对象中取出原始值,请使用该对象的 valueOf()
方法,而不是使用 Boolean()
函数。
¥If you need to take the primitive value out from the wrapper object, instead of using the Boolean()
function, use the object's valueOf()
method instead.
const bfalse = new Boolean(false);
bfalse.valueOf(); // false
创建初始值为 true
的 Boolean
对象
规范
Specification |
---|
ECMAScript Language Specification # sec-boolean-constructor |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also