【问题标题】:Why ! operator returns true for different expressions?为什么 !运算符为不同的表达式返回true?
【发布时间】:2020-07-12 23:54:08
【问题描述】:

考虑以下 javascript

var test = ['1', '2', '3'];

在控制台中,输入

test.indexOf('1') > -1;

结果为真。

现在添加基本的 Not 运算符!。

!test.indexOf('1') > -1;

结果也是正确的,但我预计结果是错误的。为什么是真的?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    这是因为!operator precedence> 高,所以首先,test.indexOf() 的结果被否定,在你的例子中导致 0 被否定,所以它变成了true。然后在不等式的上下文中使用它,它将true 转换为1 以进行比较。作为1 > -1,你会得到true的结果。

    【讨论】:

      【解决方案2】:

      你得到了true,因为你否定了左手值

       !test.indexOf('1')
      

      不是整个表达方式

       !(test.indexOf('1') > -1). 
      

      换句话说:

      !test.indexOf('1') > -1  // expected true
      

      不一样

      !(test.indexOf('1') > -1) // expected false
      

      像数学语句:

      5*2+2 // not the same as 5*(2+2) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-28
        • 1970-01-01
        • 2016-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-23
        • 1970-01-01
        相关资源
        最近更新 更多