當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


d3.js bisect()用法及代碼示例

bisect()函數是D3.js中的內置函數,該函數接受一個值作為其參數之一,並返回索引以將該元素插入作為另一個參數傳遞的數組中,以在指定範圍內或整個數組中保持排序順序。

該函數在默認情況下會在查找索引時考慮整個數組,除非通過將start和end作為參數傳遞給函數來指定範圍。

該二進製函數搜索值並檢查它是否已在範圍內。如果找到,它將被插入到該元素的左側。

用法:

d3.bisect(array, value, start, end)

參數:該函數接受上麵提到的和下麵描述的四個參數:



  • array:此強製參數包含一個元素數組。
  • value:這也是必填參數,其中包含要在數組中插入的值。
  • start:這是一個可選參數,用於指定範圍的起始索引。
  • end:這是一個可選參數,用於指定範圍的最後一個索引。

返回值:該函數返回一個整數值,該整數值表示需要在數組中插入值以保持排序順序的索引。

以下程序說明了d3.bisect()函數的用法:

範例1:該程序說明了僅傳遞兩個必需參數的d3.bisect()的用法。

<!DOCTYPE html>  
<html>  
    
<head>  
    <title>D3.js d3.bisect() Function</title>  
    
    <script src='https://d3js.org/d3.v4.min.js'> 
    </script>  
</head>  
    
<body>  
    <script>  
        var array = [42, 43, 53, 61, 71, 87, 91];  
        var value1 = 63;  
        var pos = d3.bisect(array, value1);  
        document.write(value1 + " needs to be inserted at "   
        + pos + "<br>");  
    
        var value2 = 80;  
        var pos2 = d3.bisect(array, value2);  
        document.write(value2 + " needs to be inserted at "   
        + pos2);  
    </script>  
</body>  
    
</html>

輸出:

63 needs to be inserted at 4
80 needs to be inserted at 5

範例2:該程序說明了將所有四個參數傳遞給該函數的d3.bisect()的用法。

<!DOCTYPE html>  
<html>  
    
<head>  
    <title>D3.js d3.bisect() Function</title>  
    
    <script src='https://d3js.org/d3.v4.min.js'> 
    </script>  
</head>  
    
<body>  
    <script>  
        var array = [42, 34, 27, 
         53, 61, 71, 33, 51, 87, 91];  
        var value1 = 63;  
        var pos = d3.bisect(array, value1, 2, 5);  
        document.write(value1 + " needs to be inserted at "   
        + pos + "<br>");  
    
        var pos2 = d3.bisect(array, value1, 6, 9);  
        document.write(value1 + " needs to be inserted at "   
        + pos2);  
    </script>  
</body>  
    
</html>

輸出:

63 needs to be inserted at 5
63 needs to be inserted at 8

參考:https://devdocs.io/d3~5/d3-array#bisect




相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 D3.js bisect() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。