【问题标题】:JavaScript: what is the meaning of "!!"? [duplicate]JavaScript:“!!”是什么意思? [复制]
【发布时间】:2014-09-22 17:04:04
【问题描述】:

我刚刚遇到了这个

var strict = !! argStrict;

我不禁好奇,!! 是什么意思?是双重否定吗?看起来很多余,php.js 的人不太可能在这种情况下使用它?

来源:http://phpjs.org/functions/in_array/

【问题讨论】:

  • @YuriyGalanter 这个网站的目的是成为比谷歌更好的编程知识库。为此,“只是谷歌它”等没有帮助。
  • @jcollum 我的链接的目的是一条信息“先做一些你自己的研究。所以不是固定答案机器”。而且它被重复的问题/答案所污染
  • 好点 - SO 是人们弄清楚术语是什么的好地方。如果你从来没有听说过双重否定,你就不能用谷歌搜索双重否定。
  • 相当于Boolean(argStrict),可能更易读。

标签: javascript


【解决方案1】:

它强制类型成为真正的布尔值而不是“真实”值。 例子:

var a = (1 === true) // comes out as false because 1 and true are different types and not exactly the same

var b = ((!!1) === true) // comes out as true because the 1 is first converted to a boolean value by means of negation (becomes false) and then negated a second time (becomes true)

【讨论】:

    【解决方案2】:

    这基本上意味着“转换为布尔值”。

    它两次否定它,所以它@98​​7654321@ 是“假”,然后!argStrict 是真的,!!argStrictfalse

    【讨论】:

      【解决方案3】:

      它返回一个boolean 值。 falseundefinednull0''true 任何 truthy 值。

      【讨论】:

        【解决方案4】:

        这是slacker parsing 的示例。

        如果你有一个变量,例如一个字符串,并且你想把它转换成一个布尔值,你可以这样做:

        if (myString) {
            result = true;
        }
        

        这表示,如果 myString 不是未定义、null、空、数字 0、布尔值 false,则将我的字符串设置为布尔值为 true...

        但它更快,更酷的是双打:

        result = !! myString;
        

        其他例子包括......

        //Convert to number
        result = +myString;
        
        //Bang Bang Wiggle - coerces an indexOf check into a boolean
        result !!~myString.indexOf('e');
        

        【讨论】:

          猜你喜欢
          • 2015-07-15
          • 2018-07-17
          • 2011-04-16
          • 2014-07-28
          • 1970-01-01
          • 1970-01-01
          • 2014-01-23
          • 1970-01-01
          • 2016-11-19
          相关资源
          最近更新 更多