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


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

D3.js中的bisector()函數用於使用指定的訪問器或比較器函數返回新的平分線。此方法可用於將對象數組二等分,而不僅限於簡單的基元數組。

用法:

d3.bisector(accessor)
d3.bisector(comparator)

參數:此函數僅接受上麵提到並在下麵描述的一個參數:

  • accessor/comparator:該參數可以是訪問器或比較器函數。

返回值:此函數返回新的平分線。

下麵給出了上述函數的一些示例。



範例1:該程序使用訪問參數說明了d3.bisector()的用法。

<!DOCTYPE html>  
<html>  
    
<head>  
    <title>D3.js d3.bisector() Function</title>  
    
    <script src='https://d3js.org/d3.v4.min.js'> 
   </script>  
</head>  
    
<body>  
    <script>  
        var data = [ 
          {date:new Date(2011, 1, 1), value:0.5}, 
          {date:new Date(2012, 2, 1), value:0.6}, 
          {date:new Date(2013, 3, 1), value:0.7}, 
          {date:new Date(2014, 4, 1), value:0.8} 
        ];  
    
        var bisectDate =  
d3.bisector(function(d) { return d.date; }).left;  
        var dat = new Date(2014, 4, 1); 
        document.write(bisectDate(data, dat));  
    </script>  
</body>  
    
</html>

輸出:

3

範例2:該程序使用比較器函數參數說明了d3.bisector()的用法。

<!DOCTYPE html>  
<html>  
    
<head>  
    <title>D3.js d3.bisector() Function</title>  
    
    <script src='https://d3js.org/d3.v4.min.js'> 
    </script>  
</head>  
    
<body>  
    <script>  
        var data = [ 
          {date:new Date(2011, 1, 1), value:0.5}, 
          {date:new Date(2012, 2, 1), value:0.6}, 
          {date:new Date(2013, 3, 1), value:0.7}, 
          {date:new Date(2014, 4, 1), value:0.8} 
        ];  
    
        var bisectDate =  
d3.bisector(function(d, x) { return d.date - x; }).right; 
        var dat = new Date(2014, 4, 1); 
        document.write(bisectDate(data, dat));  
    </script>  
</body>  
    
</html>

輸出:

4




相關用法


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