【问题标题】:Summing a series of numbers using reduce使用reduce对一系列数字求和
【发布时间】:2015-12-23 09:35:02
【问题描述】:

问题

我正在进行 AJAX 调用以获取数据并使用 for 循环遍历一系列项目。我已经到了使用bids[i].Bids 获得所有数字的地步,但我希望使用reduce() 对所有值求和

我已经尝试过下面的 sn-p,但它并没有将所有数字相加

scripts.js

    /*-------------------------------------
    STEP ONE: PLACE BID
    --------------------------------------*/

  $.ajax({
   url: "https://sheetsu.com/apis/4a8eceba",
   method: "GET",
   dataType: "json"
 }).then(function(spreadsheet) {


  /*-------------------------------------
  SUM BIDS IN ARRAY
  --------------------------------------*/

  var bids = spreadsheet.result;

  for (i = 0; i < bids.length; i++) {
    var allBids = bids[i].Bids; // List of all the bids
    console.log(allBids);
  }

看着documentation,我看到这个例子是对一个数组的所有值求和。

var total = [0, 1, 2, 3].reduce(function(a, b) {
  return a + b;
});
// total == 6 

【问题讨论】:

    标签: javascript jquery ajax for-loop sum


    【解决方案1】:

    由于您有一个 对象数组,您需要稍微修改 reduce 函数来汇总各个对象的 Bids 属性:

    var bids = spreadsheet.result;
    
    var total = bids.reduce(function(prev, curr) {
        return prev + curr.Bids;
    }, 0);
    

    【讨论】:

    • 当我尝试这个时,我得到的数字 005050025050025 都集中在一起
    • 也许我遗漏了什么,你为什么要循环?
    • 我想我想知道您是否可以更详细地解释reduce函数的作用,因为我得到的是打印到控制台的一串数字,而不是那些被求和的数字.我在之前的代码中尝试进行的一项更改是在 for 循环中将 totalBids 更改为 var totalBids = parseInt(bids[i].Bids)
    • 所以现在,我基本上得到了一串数字005050025050025,而不是总和。
    猜你喜欢
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多