【问题标题】:What is the purpose of using ~ in JavaScript?在 JavaScript 中使用 ~ 的目的是什么?
【发布时间】:2015-04-08 01:09:11
【问题描述】:

我正在尝试阅读Zepto.js 的源代码。而且函数matches中有一个地方我不明白:

zepto.matches = function(element, selector) {
    if (!selector || !element || element.nodeType !== 1) return false
    var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
                          element.oMatchesSelector || element.matchesSelector
    if (matchesSelector) return matchesSelector.call(element, selector)
    var match, parent = element.parentNode, temp = !parent
    if (temp) (parent = tempParent).appendChild(element)

    //Here is my question. This line used the `~`
    match = ~zepto.qsa(parent, selector).indexOf(element)
    temp && tempParent.removeChild(element)
    return match
} 

函数matches 用于确定元素是否与提供的选择器匹配。它应该返回一个布尔值。

zepto.qsa() 是 Zepto 的 CSS 选择器实现,它使用 document.querySelectorAll 和其他一些优化。

所以。下面代码中~的作用是什么?

match = ~zepto.qsa(parent, selector).indexOf(element)

我知道~ 的意思是Bitwise NOT

并且(根据我自己的测试):

~ -1 === 0

~ 0 === -1

~ 1 === -2

但我还是不明白这个设计是干什么用的。

谁能解释一下?

【问题讨论】:

标签: javascript zepto


【解决方案1】:

它使用bitwise NOT 运算符来反转indexOf() 函数的结果。

我不熟悉 zepto.js,但我可以猜测代码在做什么。首先它调用zepto.qsa() 方法并传递父对象和选择器。这个方法必须返回一个数组,因为它会调用indexOf() 来获取元素的索引(我假设它是被“匹配”的元素)。

如果在集合中找不到元素,Array.indexOf() 方法将返回 -1。正如您已经看到的那样,-1 上的按位非给您零,相当于falseAny other value that could come out would be equivalent to true.

更一般地说,这意味着您可以在 indexOf() 上使用按位 NOT 获取一个布尔值,指示搜索的元素是否存在于 收藏与否。

【讨论】:

  • 谢谢。我现在意识到了。我刚刚在自己的测试中使用了~arr.indexOf( x ) == true。所以我搞混了。
【解决方案2】:

嗯.. 它是按位 NOT,因此您可以在处理位时使用它。

至于您通常不会发现自己使用比特的实际应用,这里有一个小技巧:

 if (~arr.indexOf(val)) doStuff();

 //instead of

 if (arr.indexOf(val) > -1) doStuff();

--编辑--

我意识到我没有看到您要求解释将 ~indexOf 一起使用。简单地说,~-1 的计算结果为 0。当您使用 if 语句时,0 是一个错误值。这是写arr.indexOf(val) > -1的简写方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    相关资源
    最近更新 更多