if("test")
和if(!!"test")
什么区别,只判断是假还是真;
The question has a double negation expressson, that converts the type to boolean.
eg
var x = "test";
x === true; // evaluates to false
var x = !!"test";
x === true; //evalutes to true
!! will convert a "truthy" value in true, and a "falsy" value on false.
"Falsy" values are the following:
false
0
(zero) ""
(empty string) null
undefined
NaN
If a variable x
has any of these, then !!x
will return false
. Otherwise, !!x
will return true
.
On the practical side, there's no difference between doing if(x)
and doing if(!!x)
, at least not in javascript: both will enter/exit the if in the same cases.
EDIT: See http://www.sitepoint.com/blogs/2009/07/01/javascript-truthy-falsy/ for more info
!! does type conversion to a boolean, where you are just dropping it in to an if, it is AFAIK, pointless.
There is no functional difference. As others point out,
!!"test"
converts to string to a boolean.
Think of it like this:
!(!("test"))
First, "test"
is evaluated as a string. Then !"test"
is evaluated. As !
is the negation operator, it converts your string to a boolean. In many scripting languages, non-empty strings are evaluated as true, so !
changes it to a false. Then !(!"test")
is evaluated, changing false to true.
But !!
is generally not necessary in the if condition as like I mention it already does the conversion for you before checking the boolean value. That is, both of these lines:
if ("test")
if (!!"test")
are functionally equivalent.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.