在javascript中双重否定(!!) - 目的是什么? [英] Double negation (!!) in javascript - what is the purpose?
问题描述
我遇到过这段代码
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?
(代码来自 https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js )
推荐答案
它转换为布尔值。第一个!
否定它一次,转换值如下:
It casts to boolean. The first !
negates it once, converting values like so:
-
未定义
至true
-
null
到true
-
+0
到true
-
-0
totrue
-
''
至true
-
NaN
至true
-
false
totrue
- 所有其他表达式
false
undefined
totrue
null
totrue
+0
totrue
-0
totrue
''
totrue
NaN
totrue
false
totrue
- All other expressions to
false
然后另一个!
再次否定它。简单的转换为布尔值,完全等同于 ToBoolean ,仅仅因为!
定义为否定。但是,这里没有必要,因为它仅用作条件运算符的条件,它将以相同的方式确定真值。
Then the other !
negates it again. A concise cast to boolean, exactly equivalent to ToBoolean simply 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.
这篇关于在javascript中双重否定(!!) - 目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!