当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。