javascript 中的双重否定 (!!) - 目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10467475/
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
Double negation (!!) in javascript - what is the purpose?
提问by Eran Medan
Possible Duplicate:
What is the !! (not not) operator in JavaScript?
I have encountered this piece of code
我遇到过这段代码
function printStackTrace(options) {
options = options || {guess: true};
var ex = options.e || null, guess = !!options.guess;
var p = new printStackTrace.implementation(), result = p.run(ex);
return (guess) ? p.guessAnonymousFunctions(result) : result;
}
And couldn't help to wonder why the double negation? And is there an alternative way to achieve the same effect?
不禁想知道为什么要双重否定?有没有其他方法可以达到同样的效果?
(code is from https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js)
(代码来自https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js)
回答by Ry-
It casts to boolean. The first !
negates it once, converting values like so:
它转换为布尔值。第一个!
否定它一次,像这样转换值:
undefined
totrue
null
totrue
+0
totrue
-0
totrue
''
totrue
NaN
totrue
false
totrue
- All other expressions to
false
undefined
到true
null
到true
+0
到true
-0
到true
''
到true
NaN
到true
false
到true
- 所有其他表达式
false
Then the other !
negates it again. A concise cast to boolean, exactly equivalent to ToBooleansimply because !
is defined as its negation. It's unnecessary here, though, because it's only used as the condition of the conditional operator, which will determine truthiness in the same way.
然后另一个!
再次否定它。对布尔值的简洁转换,完全等同于ToBoolean仅仅因为!
被定义为它的否定。但是,这里没有必要,因为它仅用作条件运算符的条件,它将以相同的方式确定真实性。
回答by gdoron is supporting Monica
var x = "somevalue"
var isNotEmpty = !!x.length;
Let's break it to pieces:
让我们把它分解成碎片:
x.length // 9
!x.length // false
!!x.length // true
So it's used convert a "truethy" \"falsy" value to a boolean.
因此,它用于将“truethy”\“falsy”值转换为布尔值。
The following values are equivalent to false in conditional statements:
以下值在条件语句中等效于 false :
- false
- null
- undefined
- The empty string
""
(\''
) - The number 0
- The number NaN
- 错误的
- 空值
- 不明确的
- 空字符串
""
(\''
) - 数字 0
- 数字 NaN
All other values are equivalent to true.
所有其他值都等价于 true。
回答by Jamie Treworgy
Double-negation turns a "truthy" or "falsy" value into a boolean value, true
or false
.
双重否定将“真”或“假”值转换为布尔值,true
或false
.
Most are familiar with using truthiness as a test:
大多数人都熟悉使用真实性作为测试:
if (options.guess) {
// runs if options.guess is truthy,
}
But that does not necessarily mean:
但这并不一定意味着:
options.guess===true // could be, could be not
If you need to force a "truthy" value to a true boolean value, !!
is a convenient way to do that:
如果您需要将“真实”值强制为真正的布尔值,这!!
是一种方便的方法:
!!options.guess===true // always true if options.guess is truthy