javascript - 理解 modenizer 包含函数

标签 javascript operators modernizr

我刚刚浏览了 modenizer 的代码并遇到了以下功能:

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

modenizer 有很多用于小测试的小函数。现在来问我的问题,我确实明白 double equal 是为了将所有内容都转换为 bool 值,但是什么是 !!~ 也是什么

''  

str 之前 ??

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

最佳答案

!!~('' + str)

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

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

  3. '' + 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/

相关文章:

javascript - Material Design lite 对话框在 Safari 桌面和手机中呈现

c# - 或整数

C++ 运算符代码继承出现问题 : am I require to copy same code for all derived classes?

css - 对 modernizr 有用的 LESS CSS 语法

javascript - 创建以逗号分隔的字符串

jquery click 事件的 Javascript 变量范围问题

javascript - 当用户向下滚动我的网页时,如何删除 chrome 地址栏周围的边框

f# - F# 中自定义运算符的优先级

html - 图片 :first-of-type selects all images

browser - 是否可以检查是否使用modernizr启用了cookie?