admin管理员组文章数量:1426953
I was examining the src of underscore.js and discovered this:
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
Why was "!!" used? Should it be read as NOT-NOT or is there some esoteric JS nuance going on here?
I was examining the src of underscore.js and discovered this:
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
Why was "!!" used? Should it be read as NOT-NOT or is there some esoteric JS nuance going on here?
Share Improve this question edited Apr 19, 2015 at 10:52 niton 9,20923 gold badges35 silver badges56 bronze badges asked Jun 27, 2011 at 22:14 BlahBlah 391 bronze badge 2-
1
It's called a shorthand, not an esoteric JS nuance. In the same way that the
+
operator is used to convert to a number (e.g.:+"0"
) and that+""
is used to convert to a string. – HoLyVieR Commented Jun 27, 2011 at 23:25 - 1 possible duplicate of What is the !! operator in JavaScript? – Crescent Fresh Commented Jun 28, 2011 at 1:15
4 Answers
Reset to default 12It is just an obtuse way to cast the result to a boolean.
Yes, it's NOT-NOT. It is monly used idiom to convert a value to a boolean of equivalent truthiness.
JavaScript understands 0.0
, ''
, null
, undefined
and false
as falsy, and any other value (including, obviously, true
) as truthy. This idiom converts all the former ones into boolean false
, and all the latter ones into boolean true
.
In this particular case,
a && b
will return b
if both a
and b
are truthy;
!!(a && b)
will return true
if both a
and b
are truthy.
The && operator returns either false or the last value in the expression:
("a" && "b") == "b"
The || operator returns the first value that evaluates to true
("a" || "b") == "a"
The ! operator returns a boolean
!"a" == false
So if you want to convert a variable to a boolean you can use !!
var myVar = "a"
!!myVar == true
myVar = undefined
!!myVar == false
etc.
It is just two ! operators next to each other. But a double-negation is pointless unless you are using !! like an operator to convert to Boolean type.
It will convert anything to true or false...
本文标签: Javascript Logical OperatorStack Overflow
版权声明:本文标题:Javascript Logical Operator:? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745476805a2659999.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论