• The tilde ( ~ ) operator in JavaScript


    From the JavaScript Reference on MDC,

    ~ (Bitwise NOT)

    Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one’s complement) of a. The truth table for the NOT operation is:

    a NOT a
    0 1
    1 0

    Example:

    9 = 00000000000000000000000000001001 (base 2)
                   --------------------------------
    ~9 = 11111111111111111111111111110110 (base 2) = -10 (base 10)

    Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

    Now lets look at the Logical NOT(!)

    ! (Logical NOT)

    Returns false if its single operand can be converted to true; otherwise, returns true. 

    Mixing the two NOT operators together can produce some interesting results:

    !~(-2) = false

    !~(-1) = true

    !~(0) = false

    !~(1) = false

    !~(2) = false

    For all integer operands except -1, the net operand after applying the ~ operator for the ! operator would be truthy in nature resulting in FALSE.

    -1 is special because ~(-1) gives 0 which is falsy in JavaScript. Adding the ! operator gives us the only TRUE.

    When to use this special case ?

    A lot of times in JavaScript String manipulation, you are required to search for a particular character in a string. For example,

    1 var str = 'posterous';
    2  
    3 if ( str.search('t') >= 0 ) {
    4 // character t found
    5 }
    6 else{
    7 // not found
    8 }

    We can use the operators instead of the comparison operators, like this:

    1 var str = 'posterous';
    2  
    3 if ( !~str.search('t') ) {
    4 // character 't' not found branch
    5 }
    6 else{
    7 // found branch
    8 }

     

    原帖地址:http://www.javascriptturnsmeon.com/the-tilde-operator-in-javascript/
  • 相关阅读:
    C++11特性
    DBC文件小结
    关于宏定义
    CentOS 6.5下Zabbix的安装配置
    CentOS下搭建LAMP环境详解
    VS2010中汉字拷贝到Word出现乱码问题解决
    DLL注入
    数组赋值
    CDC的StretchBlt函数载入位图时图片失真问题
    2019年下半年Web前端开发初级理论考试
  • 原文地址:https://www.cnblogs.com/mliudong/p/4022219.html
Copyright © 2020-2023  润新知