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 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;
========================================================== ========================================================== ==================================
The following is a simple example:
Var o = {flag: true };
Var test = !! O. flag; // equivalent to var test = o. flag | false;
Alert (test );
Because it is used for null and undefined! The true result is generated when the operator is used, so the purpose of using two exclamation points is that if the flag value in o is explicitly set (non-null/undefined/0 "/equivalent ), naturally, the test will be followed by o. the flag value is the same. If not set, test defaults to false instead of null or undefined.
A classic example of jQuery is as follows: (jQuery 1.7.0.js: Line 748)
Grep: function (elems, callback, inv ){
Var ret = [], retVal;
Inv = !! Inv;
// Go through the array, only saving the items
// That pass the validator function
For (var I = 0, length = elems. length; I <length; I ++ ){
RetVal = !! Callback (elems [I], I );
If (inv! = RetVal ){
Ret. push (elems [I]);
}
}
Return ret;
}
When using the grep function, if the third parameter is given and is not null/undefined/0 "/equivalent, inv is true; otherwise, it is false. The purpose of this operation is to ensure that the values of inv and retVal can only be obtained in true/false, rather than other values, to facilitate subsequent judgment.