SoFunction
Updated on 2025-02-28

Using javascript: Detailed solution to convert other types of values ​​into boolean types of values

1.Use Boolean objects for conversion

Copy the codeThe code is as follows:

var num123 = 123, str = 'abc', o = {name:'test'}, num0 = 0; num123 = Boolean(num123); //true num0 = Boolean(num0); //false str = Boolean(str); //true o = Boolean(o); //true

2.Using two '!' operators, the first '!' converts the value into a boolean value and takes the non-value of its value, and the second '!' restores its boolean value, similar to the principle of "negative negative and positive".

Copy the codeThe code is as follows:

var num123 = 123, str = 'abc', o = {name:'test'}, num0 = 0; num123 = !!(num123); //true num0 = !!(num0); //false str = !!(str); //true o = !!(o); //true

The results obtained are the same as method 1.

Finally, you need to know: Any javascript value can be converted into a boolean value. The following values ​​will be converted to false:

Copy the codeThe code is as follows:

undefined,null,0,-0,NaN,"" //Empty string

Need to pay attentionThe '0' string containing only 0 will be converted to true!

Add to the particularity of null and undefined:

Copy the codeThe code is as follows:

null == undefined //true null === undefined //false