在javascript中`~`意味着什么 [英] what does `~` mean in javascript

查看:221
本文介绍了在javascript中`~`意味着什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了express的代码,并查看此代码 https:// github。 com / visionmedia / express / blob / master / lib / application.js#L490

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);

在<$ c之前的含义$ c> envs

推荐答案

如果您想知道为什么在这种情况下使用它,它是查找 indexOf 方法的简写。

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 当它找不到东西时返回-1,当它没有时返回> = 0。所以当你做~~你得到0(一个假值),当你做任何其他事情时,你得到一个真正的价值。

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.

所以:

if( ~str.indexOf( "something" ) ) {
...
}

是一种较短的说法

if( str.indexOf( "something" ) !== -1 ) {
...
}

如果您想知道如何-1是0的NOT,那么请阅读这里

If you are wondering how is -1 the NOT of 0, then read here

这篇关于在javascript中`~`意味着什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆