Double negation (!!) in JavaScript - what is the purpose?

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 I couldn't help to wonder why the double negation? And is there an alternative way to achieve the same effect?

(The code is from https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js.)

82052 次浏览
var x = "somevalue"
var isNotEmpty = !!x.length;

让我们把它打碎:

x.length   // 9
!x.length  // false
!!x.length // true

因此,它被用来将一个“真实的”“虚假的”值转换为一个布尔值。


以下值在 条件语句中等效于 false:

  • 假的
  • 无效
  • 未定义
  • 空字符串 ""('')
  • 数字0
  • 号码 NaN

所有 其他值都等效于 true。

它强制转换为布尔值,第一个 !负一次,转换值如下:

  • undefined呼叫 true
  • null呼叫 true
  • +0呼叫 true
  • -0呼叫 true
  • ''呼叫 true
  • NaN呼叫 true
  • false呼叫 true
  • 所有其他表达式到 false

然后另一个 !再次否定它。简洁的布尔转换,完全等价于 布尔型,因为 !定义为否定。不过在这里没有必要,因为它只是用来作为条件运算符的条件,这也会以同样的方式决定真实性。

双重否定将“真值”或“假值”转换为布尔值,即 truefalse

大多数人都熟悉用真实性作为测试:

if (options.guess) {
// Runs if 'options.guess' is truthy,
}

但这并不一定意味着:

options.guess === true   // Could be, could be not

如果您需要将“ truthy”值强制转换为真正的布尔值,!!是一种方便的方法:

!!options.guess === true   // Always true if 'options.guess' is truthy