双感叹号 (!!) 在 javascript 中是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29312123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does the double exclamation (!!) work in javascript?
提问by wordsforthewise
I'm going through the Discover Meteor demo, and am struggling to figure out how exactly 'return !! userId;' works in this section:
我正在浏览 Discover Meteor 演示,并且正在努力弄清楚“返回 !! 用户身份;' 在本节工作:
Posts.allow({
insert: function(userId, doc) {
// only allow posting if you are logged in
return !! userId;
}
});
回答by Jordan Running
!is the logical negation or "not" operator. !!is !twice. It's a way of casting a "truthy" or "falsy" value to trueor false, respectively. Given a boolean, !will negate the value, i.e. !trueyields falseand vice versa. Given something other than a boolean, the value will first be converted to a boolean and then negated. For example, !undefinedwill first convert undefinedto falseand then negate it, yielding true. Applying a second !operator (!!undefined) yields false, so in effect !!undefinedconverts undefinedto false.
!是逻辑否定或“非”运算符。!!是!两次。这是一种分别将“真”或“假”值投射到trueor 的方法false。给定一个布尔值,!将否定该值,即!true产生false,反之亦然。给定布尔值以外的值,该值将首先转换为布尔值,然后取反。例如,!undefined将首先转换undefined为false然后否定它,产生true. 应用第二个!运算符 ( !!undefined) 会产生false,因此实际上!!undefined转换undefined为false。
In JavaScript, the values false, null, undefined, 0, -0, NaN, and ''(empty string) are "falsy" values. All other values are "truthy."(1):7.1.2Here's a truth table of !and !!applied to various values:
在JavaScript中,价值观false,null,undefined,0,-0,NaN,和''(空字符串)是“falsy”的价值观。所有其他值都是“真实的”。(1):7.1.2这里的真值表!和!!应用于各种值:
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

