what's the " !~" mean in javascript
This question already has an answer here:
tl;dr
indexOf
returns -1 when an element cannot be found in an array. Therefore, the if
statement is checking if name
could not be found in names
. !~-1 ==> true
Longer version:
The tilde ( ~
) operator (bitwise NOT) yields the inverted value (aka one's complement) of a. [Source] For example, ~-1 === 0
. Note that 0 == false
and !0 === true
. indexOf
returns -1 when an element cannot be found in an array. Therefore, we can use !~-1 === true
to find out if indexOf
could not find name
in names
(ie returned -1).
My opinion:
As you can see, using these obfuscated or "clever" techniques without comments can really confuse the reader. If you do love these techniques, please document what your line(s) of code are doing for the sake of the readers!
! (Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.
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.
链接地址: http://www.djcxy.com/p/75042.html