We often see this example: zookeeper
Copy codeThe Code is as follows:
Var;
Var B = !! A;
A is undefined by default .! A is true ,!! A is false, so the value of B is false, not undefined or another value, which is mainly to facilitate subsequent judgment.
!! It is generally used to forcibly convert the following expression to a boolean data (boolean), that is, it can only be true or false;
Javascript is a weak type language (the variable does not have a fixed data type), so sometimes it needs to be forcibly converted to the corresponding type, similar:
Copy codeThe Code is as follows:
A = parseInt (1234 ″)
A = "1234"-0 // convert to a number
B = 1234 + "" // convert to a string
C = someObject. toString () // convert the object to a string
Among them, 1st and 4th are Explicit conversions, and 2 and 3 are implicit conversions.
Boolean conversion. The javascript Convention rule is
False, undefinded, null, 0, "is false
True, 1, "somestring", [Object] is true
For other values such as null and undefined that are implicitly converted, use! The true result is generated when the operator is used. Therefore, the function of Using Two exclamation points is to convert these values into "equivalent" Boolean values;
Let's take a look:
Copy codeThe Code is as follows:
Var foo;
Alert (! Foo); // In the case of undifined, true is returned for an exclamation point;
Alert (! Goo); // null, true is returned for an exclamation point;
Var o = {flag: true };
Var test = !! O. flag; // equivalent to var test = o. flag | false;
Alert (test );
In this example, when undifined and null are used, true is returned with an exclamation point, and false is returned with two exclamation points. Therefore, the role of the Two exclamation points is, if the variable value is explicitly set (non-null/undifined/0/"" equivalent), the result is returned based on the actual value of the variable. If no value is set, the result returns false.