JavaScript Bool...LOGIN

JavaScript Boolean object

JavaScript Boolean Object

Boolean object is also called a Boolean object, and its meaning is to represent two aspects of logic: true (true) and false (false). The syntax for creating a Boolean object is as follows:

//Constructor function
new Boolean(value);
//Conversion function
Boolean(value);

The value parameter can be the value to be converted into a Boolean object, or the value stored in the Boolean object. The difference between the above two syntaxes can be seen through the following example:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<script type="text/javascript">
    document.write( typeof(new Boolean(1)) + '<br />' );
    document.write( typeof(Boolean(1)) );
</script>
</head>
<body>
</body>
</html>

Run this example, the output is:

object
boolean


It can be seen that using the constructor (new keyword) gets an object containing a Boolean value; and using the conversion function, we get is a Boolean value.

Summary: The Boolean object is a relatively special object. We can regard it as a container that wraps Boolean values.

Tip

If the value parameter is set to 0, -0, null, "", false, undefined or NaN, or the value parameter is omitted Parameter, the Boolean object is set to false, otherwise it is true.

Note that although the Boolean object is set to false, it is still true in the if judgment:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<script type="text/javascript">
var obj1 = new Boolean(false);
if( obj1 ){
document.write( '1' );
}else{
document.write( '2' );
}
</script>
</head>
<body>
</body>
</html>

Running this example will output 1 . The reason is that although obj1 is an object set to false, when the if is judged, obj1 is a non-empty object, so it is considered meaningful, true is returned and the judgment is established. This has nothing to do with the boolean value the obj1 object contains.

Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var b1=new Boolean(0); var b2=new Boolean(1); var b3=new Boolean(""); var b4=new Boolean(null); var b5=new Boolean(NaN); var b6=new Boolean("false"); document.write("0 is boolean "+ b1 +"<br>"); document.write("1 is boolean "+ b2 +"<br>"); document.write("An empty string is boolean "+ b3 + "<br>"); document.write("null is boolean "+ b4+ "<br>"); document.write("NaN is boolean "+ b5 +"<br>"); document.write("The string 'false' is boolean "+ b6 +"<br>"); </script> </head> <body> </body> </html>
submitReset Code
ChapterCourseware