Home >Web Front-end >JS Tutorial >How to convert string to boolean type in javascript

How to convert string to boolean type in javascript

青灯夜游
青灯夜游Original
2021-07-20 12:02:5522826browse

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)".

How to convert string to boolean type in javascript

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

##1true0false##truefalse""##undefined falsenullfalseNaNfalseInfinitytrue##[Recommended learning: javascript advanced tutorial】
Convert common values ​​to Boolean values
true
false
false

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn