简体   繁体   中英

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?

将结果转换为布尔值只是一种迟钝的方法。

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...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM