如何在Javascript中创建一个函数,该函数返回一起添加的数组中所有项的总和?

时间:2015-10-21 04:00:46

标签: javascript arrays sum

我和我的朋友竞争,他告诉我 - 创建一个名为addThemAllTogether的函数,它接收一个数字数组并返回一起添加的数组中所有项的总和。

在Javascript中看起来像什么?

2 个答案:

答案 0 :(得分:2)

您还没有,JavaScript已经拥有该功能,并且它被称为Array.prototype.reduce

// set up some list of values
var list = [1,2,3,...,999,1000];

// run through the array, updating a tally value for every element we see:
var sum = list.reduce(function(runningTally, currentValue) {
  // simplest possible thing: add the current value to the tally,
  // which means at the end of the iteration the tally will the sum
  // of all elements in the array.
  return runningTally + currentValue;
}, 0)

第二个参数" 0"是运行计数的起始值。它是可选的,但通常是明确设置的好主意。

答案 1 :(得分:0)

使用for循环遍历数组

  var group1;
  $.get("http://localhost:2000/api/group1", function(data) {
    group1 = data;
    window.work();
  });

  var group2;
  $.get("http://localhost:1000/api/group2", function(data) {
    group2 = data;
    window.work();
  });

  var group3;
  $.get("http://localhost:1000/api/group3", function(data) {
    group3 = data;
    window.work();
  });

  var group4
  $.get("http://localhost:1000/api/group4", function(data) {
    group4 = data;
    window.work();
  });

  window.work = function() {
    if (group1 && group2 && group3 && group4) {
      //you code goes here.
    }
  }

working code