The usage of ! in js is relatively flexible. It is often used in addition to doing logical operations! It can be used for type judgment! To obtain a Boolean value with the above object,
1,! can convert the variable into a boolean type. The negation of null, undefined and empty string is false, and the others are true.
!null=true !undefined=true !''=true !100=false !'abc'=false
2.! ! It is often used for type judgment. After the first step! (variable), the logical negation operation is performed. In js, novices often write such bloated code:
Determine whether variable a is non-null, undefined or non-null String can execute the content of the method body
var a; if(a!=null&&typeof(a)!=undefined&&a!=''){ //a有内容才执行的代码 }
In fact, we only need to write a judgment expression:
if(!!a){ //a有内容才执行的代码... }
to achieve the same effect as above. Only when a is a variable with actual meaning, the method will be executed. Otherwise, the following code will not be executed if the variables null, undefined and '' are empty strings.
It can be concluded that "!" is a logical AND operation, and can be logically ANDed with any variable to convert it into a Boolean value. "!!" is the negation operation of logical AND, especially the latter in The code is concise and efficient when judging the type, eliminating the need for redundant code to judge null, undefined and empty strings multiple times.
Recommended tutorial: js introductory tutorial
The above is the detailed content of Introduction to the usage of ! and!! in js. For more information, please follow other related articles on the PHP Chinese website!