[英]Javascript Logical Operator:?
I was examining the src of underscore.js and discovered this: 我正在检查underscore.js的src并发现了这个:
_.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?
它应该被视为NOT-NOT还是有一些深奥的JS细微差别在这里?
将结果转换为布尔值只是一种迟钝的方法。
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. JavaScript将
0.0
, ''
, null
, undefined
和false
理解为falsy,将任何其他值(包括显然, true
)理解为真实。 This idiom converts all the former ones into boolean false
, and all the latter ones into boolean true
. 这个成语将所有前者转换为布尔值
false
,后者转换为布尔值true
。
In this particular case, 在这种特殊情况下,
a && b
will return b
if both a
and b
are truthy; 如果
a
和b
都是真实的,则返回b
;
!!(a && b)
will return true
if both a
and b
are truthy. 如果
a
和b
都是true
那么它将返回true
。
The && operator returns either false or the last value in the expression: &&运算符返回false或表达式中的最后一个值:
("a" && "b") == "b"
The || || operator returns the first value that evaluates to true
operator返回计算结果为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... 它会将任何东西转换为真或假......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.