Array.reduce()

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>JavaScript Array.reduce()</h1>
  6.  
  7. <p>此例确定数组中所有数字的总和:</p>
  8.  
  9. <p id="demo"></p>
  10.  
  11. <script>
  12. var numbers = [45, 4, 9, 16, 25];
  13. var sum = numbers.reduce(myFunction);
  14.  
  15. document.getElementById("demo").innerHTML = "总和是:" + sum;
  16.  
  17. function myFunction(total, value, index, array) {
  18. return total + value;
  19. }
  20. </script>
  21.  
  22. </body>
  23. </html>