Boolean()
The constructor can be used to create Boolean objects as well as Boolean primitives, representingtrue
orfalse
values .
In the code below, I detail the creation of Boolean values in JavaScript.
Example: sample52.html
Boolean()
ParametersBoolean()
The constructor converts an argument to a Boolean value (i.e.true
orfalse
). Any valid JavaScript value that is not 0, -0,null
,false
,NaN
,undefined
, or the empty string ("") will be converted totrue
. In the following example, we create two Boolean object values: atrue
and afalse
.
Example: sample53.html
When used with thenew
keyword, an instance from theBoolean()
constructor produces an actual complex object. You should avoid using the Boolean() constructor to create boolean values (instead use literals/raw numbers) because of potential issues related to thetypeof
operator. Thetypeof
operator reports Boolean objects as "object" instead of the original label ("boolean") as you might expect. Additionally, literal/raw values are written faster.
Boolean()
Properties and methodsBoolean()
The object has the following properties:
Properties (for example,Boolean.prototype;
):
prototype
Boolean object instances have the following properties and methods (excluding inherited properties and methods):
Instance properties (e.g.,var myBoolean = false;
myBoolean.constructor;
):
Constructor
Instance methods (e.g.,var myNumber = false;
myBoolean.toString();
):
toSource()
toString()
valueOf()
Afalse
Boolean object created from theBoolean()
constructor (rather than a primitive value) is an object, and the object is converted totrue
. Therefore, when afalse
Boolean object is created via theBoolean()
constructor, the value itself is converted totrue
. In the example below, I demonstrate how afalse
Boolean object is always "true".
Example: sample54.html
If you need to convert a non-Boolean value to a Boolean value, just use theBoolean()
constructor without thenew
keyword, and the returned value will be the original value instead Not a Boolean object.
Already mentioned, but worth mentioning again as it relates to conversions: if value is 0, -0,null
,false
,NaN
,undefined
, or an empty string ("") isfalse
. If used in a Boolean context, any value in JavaScript other than the above will be converted totrue
(i.e.if (true) {};
).
Example: sample55.html
It's critical to know which JavaScript values are simplified tofalse
so that you know that all other values are treated astrue
.
The above is the detailed content of How to determine whether it is a Boolean value. For more information, please follow other related articles on the PHP Chinese website!