开发者

Javascript Logical Operator:?

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?


It is just an obtuse way to cast the result to a boolean.


Yes, it's NOT-NOT. It is commonly 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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜