Javascript method to convert a string to a boolean type: 1. Use double logical negation "!!" and syntax "!! String"; 2. Use the Boolean() function to force the value to be converted to Boolean value, syntax "Boolean(String)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
There are 2 common ways for JavaScript to convert values to Boolean values:
Use double logical not
Use Boolean () Function
Method 1: Use double logical NOT
A logical NOT operator!
can convert the value is a Boolean value and negated, two logical NOT operators can convert the value to the correct Boolean value.
console.log(!!0); //返回false console.log(!!1); //返回true console.log(!!""); //返回false console.log(!!NaN); //返回false console.log(!!null); //返回false console.log(!!undefined); //返回false console.log(!![]); //返回true console.log(!!{}); //返回true console.log(!!function(){}); //返回true
Method 2: Use the Boolean() function
Use the Boolean() function to force the value to be converted to a Boolean value.
console.log(Boolean("0")); //返回true console.log(Boolean("1")); //返回true console.log(Boolean("")); //返回false
Attachment: Convert common values to Boolean values
true | |
false | |
true | |
false | |
false | ##undefined |
null | |
NaN | |
Infinity | |
##[Recommended learning: |
The above is the detailed content of How to convert string to boolean type in javascript. For more information, please follow other related articles on the PHP Chinese website!