理解 modenizer 包含函数

understanding modenizer contains Function

我刚刚浏览了 modenizer 的代码,发现了以下函数:

function contains(str, substr) {
    return !!~('' + str).indexOf(substr);
}

modenizer 有很多这样的小功能用于小测试。现在来问我的问题,我确实明白双重相等是为了将所有东西都转换为布尔值,但是 !!~ 是什么,

也是什么
''  

str 之前 ??

我在 SO 上看到了一些解决类似问题但不完全是这个问题的问题,有人可以解释一下在这个例子的上下文中这个函数内部发生了什么。

好东西。 ~x 不是按位。对于 -1 按位不是 0。所以 !!~ 在布尔表示中表示 'is not -1'。

!!~('' + str)

  1. !!:转换为布尔值(true/false)
  2. ~: Bitwise NOT 一元运算符通过反转操作数中的所有位来操作。反转其操作数的位。

    按位对任何数字 x 求和 -(x + 1)。

  3. 类型转换 将 str 转换为 string

运算符首先将 str 转换为 string,然后反转二进制的所有位,然后 returns 布尔结果。

示例

contains('abcd', 'd');

1. If str is not string then it is converted to string

    true + '' // "true"
    1 + ''    // "1"

2. `indexOf`
    The index of `substr` is returned.

3. `~`
    The bitwise NOT of 3 which is -(3 + 1) = -4

4. `!!`
    !!-4 = true


true will be returned.