What does a tilde do when it precedes an expression?

前端 未结 5 1590
南方客
南方客 2020-11-22 09:04
var attr = ~\'input,textarea\'.indexOf( target.tagName.toLowerCase() )
           ? \'value\'
           : \'innerHTML\'

I saw it in an answer, and

5条回答
  •  耶瑟儿~
    2020-11-22 09:54

    The ~ is Bitwise NOT Operator, ~x is roughly the same as -(x+1). It is easier to understand, sort of. So:

    ~2;    // -(2+1) ==> -3
    

    Consider -(x+1). -1 can perform that operation to produce a 0.

    In other words, ~ used with a range of number values will produce a falsy (coerce to false from 0) value only for the -1 input value, otherwise, any other truthy value.

    As we know, -1 is commonly called a sentinel value. It is used for many functions that return >= 0 values for success and -1 for failure in C language. Which the same rule of return value of indexOf() in JavaScript.

    It is common to check of presence/absence of a substring in another string in this way

    var a = "Hello Baby";
    
    if (a.indexOf("Ba") >= 0) {
        // found it
    }
    if (a.indexOf("Ba") != -1) { 
        // found it
    }
    
    if (a.indexOf("aB") < 0) { 
        // not found
    }
    if (a.indexOf( "aB" ) == -1) { 
        // not found
    }
    

    However, it would be more easily to do it through ~ as below

    var a = "Hello Baby";
    
    ~a.indexOf("Ba");         // -7   -> truthy
    if (~a.indexOf("Ba")) {   // true
        // found it
    }
    
    ~a.indexOf("aB");         // 0    -> falsy
    !~a.indexOf("aB");        // true
    if (!~a.indexOf( "aB" )) {  // true
        // not found
    }
    

    You Don't Know JS: Types & Grammar by Kyle Simpson

提交回复
热议问题