Home >Web Front-end >JS Tutorial >How to convert data to boolean value in javascript

How to convert data to boolean value in javascript

青灯夜游
青灯夜游Original
2021-10-08 16:57:546763browse

Javascript method to convert data into Boolean values: 1. Use double logical negation, the syntax "!! The value that needs to be converted"; 2. Use the Boolean() function, the syntax "Boolean (the value that needs to be converted)" ".

How to convert data to boolean value in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

There are 2 common methods for converting values ​​into Boolean values, as detailed below.

1. Use double logical NOT

A logical NOT operator! You can convert the value into a Boolean value and negate it. Two logical NOT operators can convert The value is converted 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

2. Use the Boolean() function

Use the Boolean() function to force the value to be converted to a Boolean value.

console.log(Boolean(0));  //返回false
console.log(Boolean(1));  //返回true

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to convert data to boolean value 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