双重感叹号(!!)在javascript中如何工作? [英] How does the double exclamation (!!) work in javascript?
问题描述
我正在浏览发现流星"演示,并努力弄清楚返回"的确切程度!用户身份;'可在本节中进行操作:
I'm going through the Discover Meteor demo, and am struggling to figure out how exactly 'return !! userId;' works in this section:
Posts.allow({
insert: function(userId, doc) {
// only allow posting if you are logged in
return !! userId;
}
});
推荐答案
!
是逻辑否定或非"运算符. !!
是两次!
.这是一种将真实"或虚假"值分别转换为 true
或 false
的方法.给定一个布尔值,!
将取反该值,即!true
产生 false
,反之亦然.给定除布尔值以外的其他值,该值将首先转换为布尔值,然后取反.例如,!undefined
将首先将 undefined
转换为 false
,然后将其取反,得到 true
.应用第二个!
运算符( !! undefined
)会产生 false
,因此实际上 !! undefined
会转换 undefined
到 false
.
!
is the logical negation or "not" operator. !!
is !
twice. It's a way of casting a "truthy" or "falsy" value to true
or false
, respectively. Given a boolean, !
will negate the value, i.e. !true
yields false
and vice versa. Given something other than a boolean, the value will first be converted to a boolean and then negated. For example, !undefined
will first convert undefined
to false
and then negate it, yielding true
. Applying a second !
operator (!!undefined
) yields false
, so in effect !!undefined
converts undefined
to false
.
在JavaScript中,值 false
, null
, undefined
, 0
, -0
, NaN
和''
(空字符串)是"fassy"值.所有其他值都是真值". (1):7.1.2 以下是应用于各种值的!
和 !!
的真值表:
In JavaScript, the values false
, null
, undefined
, 0
, -0
, NaN
, and ''
(empty string) are "falsy" values. All other values are "truthy."(1):7.1.2 Here's a truth table of !
and !!
applied to various values:
value | !value | !!value
-----------+--------+-------
false | true | false
true | false | true
null | true | false
undefined | true | false
0 | true | false
-0 | true | false
1 | false | true
-5 | false | true
NaN | true | false
'' | true | false
'hello' | false | true
这篇关于双重感叹号(!!)在javascript中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!