JavaScript js difference in the "!" And "!!" and Usage

js in !usage is more flexible, in addition to its logical operators often do with! Do determine the type, you can use! And the object to obtain a Boolean value,
1, !can be converted into a boolean variable type, null, undefined, and are inverted empty string is false, the rest are true.

!null=true

!undefined=true

!''=true

!100=false

!'abc'=false

2, !!is used to make the type of determination, in the first step !to do after logically inverted operation (variable), often in the js novice write such bloated code:
determining variable a non-null, non-empty string or undefined to content execution method body

var a;
if(a!=null&&typeof(a)!=undefined&&a!=''){
    //a有内容才执行的代码  
}

In fact, we just need to write a judgment expression:

if(!!a){
    //a有内容才执行的代码...  
}

And above will be able to achieve the same effect. There is a practical meaning of variables before execution method, otherwise variable null, undefined and empty string will not execute the following code.

Can be summed up, !is the logical AND operation, and can be any logical variable and converted to a Boolean value, !!it is negated logic operation, in particular the latter type code is determined in a simple and efficient, eliminating the need for multiple Analyzing null, and redundant code undefined empty string.

Published 79 original articles · won praise 89 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_39141486/article/details/103586712