在javascript中双重否定(!!) - 目的是什么? [英] Double negation (!!) in javascript - what is the purpose?

查看:113
本文介绍了在javascript中双重否定(!!) - 目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

什么是!! (不是)JavaScript中的运算符?

我遇到过这段代码

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 to true

  • '' true

  • NaN true

  • false to true

  • 所有其他表达式 false

  • undefined to true
  • null to true
  • +0 to true
  • -0 to true
  • '' to true
  • NaN to true
  • false to true
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆