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


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


D3.js中的d3.sum()函數用於返回給定數組元素的總和。如果數組為空,則返回0。

用法:

d3.sum(Array)

參數:此函數接受參數Array,該參數是要計算總和的元素數組。


返回值:它返回給定數組元素的總和。

以下程序說明了D3.js中的d3.sum()函數。

示例1:

<html> 
  
<head> 
    <title> 
      Getting sum of the elements of given array 
  </title> 
</head> 
  
<body> 
    <script src='https://d3js.org/d3.v4.min.js'> 
  </script> 
  
    <script> 
        // initialising the array of elements 
        var Array1 = [10, 20, 30, 40, 50, 60]; 
        var Array2 = [1, 2]; 
        var Array3 = [0, 1.5, 6.8]; 
        var Array4 = [.8, .08, .008]; 
  
        // Calling to d3.sum() function 
        A = d3.sum(Array1); 
        B = d3.sum(Array2); 
        C = d3.sum(Array3); 
        D = d3.sum(Array4); 
  
        // Getting sum of the given array's element 
        document.write(A + "<br>"); 
        document.write(B + "<br>"); 
        document.write(C + "<br>"); 
        document.write(D + "<br>"); 
    </script> 
</body> 
  
</html>

輸出:

210
3
8.3
0.888

示例2:

<html> 
  
<head> 
    <title> 
      Getting sum of the elements of given array 
  </title> 
</head> 
  
<body> 
    <script src='https://d3js.org/d3.v4.min.js'> 
  </script> 
  
    <script> 
        // initialising the array of elements 
        var Array1 = []; 
        var Array2 = ["a", "b", "c"]; 
        var Array3 = [1, "B", "C"]; 
        var Array4 = ["Geek", "Geeks", 2, 3, "GeeksforGeeks"]; 
  
        // Calling to d3.sum() function 
        A = d3.sum(Array1); 
        B = d3.sum(Array2); 
        C = d3.sum(Array3); 
        D = d3.sum(Array4); 
  
        // Getting sum of the given array's element 
        document.write(A + "<br>"); 
        document.write(B + "<br>"); 
        document.write(C + "<br>"); 
        document.write(D + "<br>"); 
    </script> 
</body> 
  
</html>

輸出:

0
0
1
5

注意:在上麵的輸出中,如果參數為空或字符串,則返回0;如果參數為包含一些整數值的字符串,則返回整數值的總和。

參考: https://devdocs.io/d3~4/d3-array#sum



相關用法


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