Double exclamation mark in JavaScript!! Example introduction
- 2020-03-30 03:57:01
- OfStack
!!!!! It is used to cast the following expression to a Boolean, which can only be true or false.
We often see examples of this:
var a ;
var b=!!a;
A is undefined by default. ! A is true!! A is false, so the value of b is false, not undefined, not anything else, just to make it easier to follow up.
!!!!! It is used to cast the following expression to a Boolean, which can only be true or false.
Because javascript is a weakly typed language (variables have no fixed data type), it is sometimes necessary to cast to the corresponding type, such as:
a=parseInt( " 1234 " )
a= " 1234 " -0 //Convert to Numbers
b=1234+ "" //Convert to string
c=someObject.toString() // The object Convert to string
The first and fourth are explicit conversions, and the second and third are implicit conversions
Boolean transformation, javascript convention rule is
False, undefined, null, 0, "" is false
True, 1, "somestring", [Object] is true
For null and undefined and other implicitly converted values, with! Operators always produce true, so the use of two exclamation points is to convert these values to "equivalent" Boolean values.
Here's another look:
var foo;
alert(!foo);//Undifined cases, an exclamation mark return is true;
alert(!goo);//In the case of null, an exclamation point returns true;
var o={flag:true};
var test=!!o.flag;//This is equivalent to var test= o.felag ||false;
alert(test);
This example demonstrates the undifined and null, with an exclamation mark return are true, use two exclamation mark returned is false, so the action of the two exclamation point is that if the clear set the value of a variable (not null/undifined / 0 / "and" equivalent), the result is according to the actual value of the variable to return, if not set, the results will return false.