代码之家  ›  专栏  ›  技术社区  ›  Rob P.

理解代码以确定数字是否为奇数,使用~~

  •  2
  • Rob P.  · 技术社区  · 8 年前

    具体代码行为:

    return !!(~~i & 1);
    

    我的问题是“我们为什么需要~~”

    (涉及: How to determine if a number is odd in JavaScript

    我理解每个片段。

    • !! 是否定运算符(两次),将从真/假值中得出真/假值
    • &

    但我仍然怀疑我们是否需要~,如果需要,为什么?

    我一直在用N。。toString(2)-例如:

    4.0.toString(2)
    > "100"
    4.1.toString(2)
    > "100.0001100110011001100110011001100110011001100110011"
    

    尝试并理解二进制表示是什么样子。在第二个示例中,最右边的数字是1,但当我插入4.1作为I的值时,它仍然正确地看到数字是偶数:

    !!(~~4.1 & 1)
    > false
    !!(4.1 & 1)
    > false
    

    1 回复  |  直到 8 年前
        1
  •  1
  •   ishegg    8 年前

    替补队员 ~~ 用于将字符串转换为数字,就像 !!

    var a = "4";
    console.log(typeof a + " " + a); //string
    console.log(typeof ~a + " " + a); //converts to number, but you get (a - 1)
    console.log(typeof ~~a + " " + a);  // reverses the previous operation, keeping the number type

    现在,正如您所意识到的,在这个操作中没有必要这样做,因为在Javascript中,当您这样做时 bitwise operations on strings they're first converted to numbers ,因此双颚化符变得多余。

    我怀疑这段代码的作者的意图是,你真的无法将十进制数归类为奇数或偶数,所以他只是将其转换为一个数字来去掉小数,这是