Home > Web Front-end > JS Tutorial > body text

An example of the role of double exclamation mark (!!) in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:53:02
Original
1031 people have browsed it

We often see examples like this: 

Copy code The code is as follows:

var a;
var b=!!a;

a defaults to undefined. !a is true, !!a is false, so the value of b is false, not undefined or other values, mainly to facilitate subsequent judgments.

!! Generally used to force the following expression to Boolean type data (boolean), that is, it can only be true or false;
Because JavaScript is a weakly typed language (variables are not fixed data type) so sometimes it is necessary to cast it to the corresponding type, similar to:
Copy code The code is as follows:

a=parseInt(“1234″)
a=”1234″-0 //Convert to number
b=1234 ”” //Convert to string
c=someObject. toString() //Convert the object to a string

The first and fourth types are explicit conversions, and the second and third types are implicit conversions

Boolean conversion , the JavaScript convention rules are

false, undefined, null, 0, "" is false
true, 1, "somestring", [Object] is true

for null and undefined, etc. For other implicitly converted values, using the ! operator will produce a true result, so the purpose of using two exclamation marks is to convert these values ​​into "equivalent" Boolean values;
Let's take a look again:
Copy code The code is as follows:

var foo;
alert(!foo);// In the undefined case, an exclamation point returns true;
alert(!goo);//In the null case, an exclamation mark also returns true;
var o={flag:true};
var test =!!o.flag;//Equivalent to var test=o.flag||false;
alert(test);

This example demonstrates when undiffed and null , using one exclamation point will return true, using two exclamation points will return false, so the role of two exclamation points is that if the value of the variable is explicitly set (not null/undified/0/"", etc.), the result It will be returned based on the actual value of the variable. If it is not set, the result will be false.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template