簡體   English   中英

在JavaScript中使用〜的目的是什么?

[英]What is the purpose of using ~ in JavaScript?

我正在嘗試閱讀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

但是我仍然不明白這個設計的目的。

有人可以解釋嗎?

它使用按位NOT運算符反轉indexOf()函數的結果。

我對zepto.js並不熟悉,但是我可以猜測代碼在做什么。 首先,它調用zepto.qsa()方法並傳遞父對象和選擇器。 此方法必須返回一個數組,因為它隨后調用indexOf()來獲取元素的索引(我認為這是元素被“匹配”)。

如果在集合中未找到該元素,則Array.indexOf()方法將返回-1。 正如您已經看到的-1上的按位NOT會給您零,這等效於false 可能出現的任何其他值都將等於true

更一般而言,這意味着您可以對indexOf()使用按位NOT來獲取布爾值,該布爾值指示所搜索的元素是否存在於集合中。

好吧..這不是按位的,因此您可以在使用位時使用它。

對於通常不習慣使用位的實際應用程序,這里有一個小技巧:

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

 //instead of

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

- 編輯 -

我意識到我沒有看到您要求使用~indexOf的解釋。 簡而言之, ~-1值為0 當使用if語句時, 0為假值。 這是編寫arr.indexOf(val) > -1方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM