what does `~` mean in javascript
I view the code of express, and see this code https://github.com/visionmedia/express/blob/master/lib/application.js#L490
if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);
what the ~
means before envs
In case you were wondering why it is used in that situation, it is a shorthand for finding out if indexOf
method found something.
indexOf
returns -1 when it doesn't find something, and >= 0 when it does. So when you do ~-1 you get 0 (a falsy value) and when you do it on anything else you get a truthy value.
So:
if( ~str.indexOf( "something" ) ) {
...
}
Is a shorter way of saying
if( str.indexOf( "something" ) !== -1 ) {
...
}
If you are wondering how is -1 the NOT of 0, then read here
It's the Bitwise NOT operator:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators
链接地址: http://www.djcxy.com/p/74972.html