!! It is generally used to forcibly convert the following expressions to boolean data. Because javascript is a weak language, it is sometimes required to forcibly convert it to the corresponding type !! It is generally used to forcibly convert the following expression to a boolean data (boolean), that is, it can only be true or false;
We often see this example:
The 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:
A = parseInt ("1234") a = "1234"-0 // convert to number B = 1234 + "// convert to string c = someObject. toString () // convert an 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:
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.