What does a tilde do when it precedes an expression?

前端 未结 5 1591
南方客
南方客 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:44

    Using it before an indexOf() expression effectively gives you a truthy/falsy result instead of the numeric index that's directly returned.

    If the return value is -1, then ~-1 is 0 because -1 is a string of all 1 bits. Any value greater than or equal to zero will give a non-zero result. Thus,

    if (~someString.indexOf(something)) {
    }
    

    will cause the if code to run when "something" is in "someString". If you try to use .indexOf() as a boolean directly, then that won't work because sometimes it returns zero (when "something" is at the beginning of the string).

    Of course, this works too:

    if (someString.indexOf(something) >= 0) {
    }
    

    and it's considerably less mysterious.

    Sometimes you'll also see this:

    var i = ~~something;
    

    Using the ~ operator twice like that is a quick way to convert a string to a 32-bit integer. The first ~ does the conversion, and the second ~ flips the bits back. Of course if the operator is applied to something that's cannot be converted to a number, you get NaN as a result. (edit — actually it's the second ~ that is applied first, but you get the idea.)

提交回复
热议问题