【问题标题】:Why does (~(1 << 31)) === ~(1 << 31) yet they aren't equal when converted to strings?为什么 (~(1 << 31)) === ~(1 << 31) 但在转换为字符串时它们不相等?
【发布时间】:2016-03-26 08:28:11
【问题描述】:

在 JS 中:

(~(1 << 31)) === ~(1 << 31)
> true
(~(1 << 31)).toString(2) === ~(1 << 31).toString(2)
> false

这怎么可能?我认为=== 运算符是相同实体之间的严格比较?

【问题讨论】:

标签: javascript binary tostring bitwise-operators


【解决方案1】:

由于 JS 中的操作顺序,我没有比较确切的值:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

成员访问.toString() 优先于位运算符。哎呀!

【讨论】:

    【解决方案2】:

    这是因为表达式的计算方式如下:

    (~(1 << 31)).toString(2) === ~((1 << 31).toString(2))
    //----------------------------^ see the parenthesis
    

    【讨论】:

      猜你喜欢
      • 2014-11-29
      • 2023-03-21
      • 2013-05-28
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      相关资源
      最近更新 更多