我刚刚浏览了 modenizer 的代码并遇到了以下功能:
function contains(str, substr) {
return !!~('' + str).indexOf(substr);
}
modenizer 有很多用于小测试的小函数。现在来问我的问题,我确实明白 double equal 是为了将所有内容都转换为 bool 值,但是什么是 !!~
也是什么
''
在 str
之前 ??
我在 SO 上看到了一些解决类似问题但不完全是这个问题的问题,有人可以解释一下在这个例子的上下文中这个函数内部发生了什么。
最佳答案
!!~('' + str)
!!
:转换为 bool 值(true/false
)~
:Bitwise NOT一元运算符通过反转操作数中的所有位来进行操作。反转其操作数的位。按位对任何数字 x 求和 -(x + 1)。
'' + str
: 类型转换 将 str 转换为string
运算符首先将str
转换为string
,然后反转二进制的所有位,然后返回 bool 结果。
示例
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.
关于javascript - 理解 modenizer 包含函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31042029/