1.Convert using a Boolean object
Copy 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.Use two '! 'Operator, First '! 'Convert the value to a Boolean value and take the non-value of the value. The second value '! 'Restore its Boolean value, similar to the principle of "negative Positive.
Copy 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 result obtained is the same as method 1.
Finally, you need to know: Any javascript value can be converted to a Boolean value. The following values are converted to false:
Copy codeThe Code is as follows:
Undefined, null, 0,-0, NaN, "// empty string
Note:The '0' string that only contains 0 will be converted to true!
Add the special characteristics of null and undefined:
Copy codeThe Code is as follows:
Null = undefined // true null = undefined // false