2012-06-07 40 views
2

在回顧「Crossfilter」源時,我遇到了一個使用>>的函數。以下是功能:>>在javascript中做什麼?

// Similar to bisectLeft, but returns an insertion point which comes after (to 
    // the right of) any existing entries of x in a. 
    // 
    // The returned insertion point i partitions the array into two halves so that 
    // all v <= x for v in a[lo:i] for the left side and all v > x for v in 
    // a[i:hi] for the right side. 

    function bisectRight(a, x, lo, hi) { 
    while (lo < hi) { 
     var mid = lo + hi >> 1; 
     if (x < f(a[mid])) hi = mid; 
     else lo = mid + 1; 
    } 
    return lo; 
    } 

谷歌沒有返回任何結果,我從來沒有見過這種情況。先謝謝您的幫助。

+1

這就像Math.floor(n/2)。在上面的例子中,注意'+'比位移有更高的優先級,所以'mid'將是'(lo + hi)>> 1'。 – Steve

+0

如果你有將來的疑慮,你可以試着找出運行非常簡單的代碼(比如'a = 10; alert(a >> 1);')。 –

回答

6

這是sign-propagating right shift operator

該運算符將第一個操作數位的指定數量 的權利。向右移位的過多位被丟棄。最左邊的位的副本 從左側移入。由於最新的 與前一個最左邊的位具有相同的值,因此 位(最左邊的位)不會改變。因此名稱 「sign-propagating」。

1

它做正確的按位的轉變,這是大致類似於通過向整除2^X(在你的例子 - 只要除以2找到平均值)。它是碰巧存在於多種語言中的一個bitwise operators,它使用數字的二進制表示法。它通常用於性能方面,因爲它幾乎總是比分割更快。