zoukankan      html  css  js  c++  java
  • 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/
  • 相关阅读:
    Springboot集成Junit
    springboot集成mybatis
    使用Spring Initializr快速创建Springboot工程
    Tungsten Replicator学习总结
    Java代理模式汇总
    Java定时任务的常用实现
    Java对象序列化剖析
    最适合作为Java基础面试题之Singleton模式
    MyCat源码分析系列之——结果合并
    MyCat源码分析系列之——SQL下发
  • 原文地址:https://www.cnblogs.com/mliudong/p/4022219.html
Copyright © 2011-2022 走看看