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


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

d3.scan()函數是D3.js中的內置函數,該函數線性掃描數組並根據指定的比較器返回最小元素的索引。當數組中沒有可比較的元素時,該函數返回undefined。

用法:

d3.scan(array, comparator)

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


  • array:該強製參數包含一個元素數組,這些元素的最小值要計算出來,而相應的索引要返回。
  • comparator:此參數是一個可選參數,它指定如何獲取最小元素。

返回值:該函數返回一個整數值,該值表示基於指定比較器的數組中最小元素的索引。

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

示例1:該程序說明了將d3.scan()與比較器一起使用

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>D3.js d3.scan() Function</title> 
  
    <script src='https://d3js.org/d3.v4.min.js'></script> 
</head> 
  
<body> 
    <script> 
        var array = [42, 71, 91, 67, 43, 17, 53]; 
        // To obtain the minimum element in the array 
        var ans1 = d3.scan(array, function(a, b) { 
            return a - b; 
        }); 
        document.write("Minimum element is " + array[ans1] + 
            " present at index: " + ans1 + "<br>"); 
  
        // To obtain the maximum element in the array 
        var ans2 = d3.scan(array, function(a, b) { 
            return b - a; 
        }); 
        document.write("Maximum element is " + array[ans2] + 
            " present at index: " + ans2); 
    </script> 
</body> 
  
</html>

輸出:

Minimum element is 17 present at index: 5
Maximum element is 91 present at index: 2

示例2:該程序說明了沒有比較器的d3.scan()的使用

<!DOCTYPE html>  
<html>  
      
<head>  
    <title>D3.js d3.scan() Function</title>  
      
    <script src='https://d3js.org/d3.v4.min.js'></script>  
</head>  
  
<body>  
<script>  
          
    var array = [42 , 71 , 91 , 67 , 43 , 17 , 53]; 
    // To obtain the minimum element in the array 
    var ans1 = d3.scan(array, ); 
    document.write("Minimum element is " + array[ans1] +  
    " present at index: " + ans1); 
</script>  
</body>  
  
</html>                    

輸出:

Minimum element is 17 present at index: 5

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



相關用法


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