微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript中的累积和数组,一个有效,一个无效

如何解决Javascript中的累积和数组,一个有效,一个无效

我是一个初学者,正在尝试一些关于 codewars 的 katas。我想知道是否有人可以帮助我并解释这段代码发生了什么。在这一点上,我不是在为整个练习寻找解决方案,我只是想了解为什么 constcumulativeSum 对两个不同的数组的工作方式不同。

我正在创建两个累积数组,代码适用于第一个cumulativeProfit 与起始数组 peopleInLine),一切都正确,但是当我使用它时对于第二个(cumulativeOutgoings 与起始数组 changerequired),数字是错误的。

我的 peopleInLine 数组是:[100,25,50,100,100]

我不得不承认我并不真正理解 constcumulativeSum = (sum => value => sum += value)(0) 是如何工作的。我在搜索堆栈溢出后找到了它!

非常感谢您的帮助。

function tickets(peopleInLine) {
  let changerequired = [];

  const cumulativeSum = (sum => value => sum += value)(0);

  let cumulativeProfit = peopleInLine.map(cumulativeSum);
  cumulativeProfit.splice(0,0);
  cumulativeProfit.pop();
  //return cumulativeProfit;
  //logs to console [0,125,175,275,300,325,350,450,475,525,550,650,675,700,750,850,875,900,950]

  for (let i = 0; i < peopleInLine.length; i++) {
      if (peopleInLine[i] === 25) { changerequired.push(0) }
      else if (peopleInLine[i] === 50) { changerequired.push(25) }
      else if (peopleInLine[i] === 100) { changerequired.push(75) }
  };
  //return changerequired; 
  //correctly logs to console: [75,75,75]

  let cumulativeOutgoings = changerequired.map(cumulativeSum);
  cumulativeOutgoings.splice(0,0);
  cumulativeOutgoings.pop();
  return cumulativeOutgoings;
  //incorrectly logs to console: [0,1125,1150,1225,1300,1325,1400,1425,1500,1525] 
  //should be [0,175 etc.]
};
console.log(tickets([100,100]));

解决方法

问题在于您使用 cumulativeSum 的方式您正在尝试一个函数引用并在两个数组之间使用它,因为当您调用第二个数组时,sum 已经有一些值它。修复将如下所示

function tickets(peopleInLine) {
  let changeRequired = [];

  const cumulativeSum = (sum => value => sum += value);

  let cumulativeProfit = peopleInLine.map(cumulativeSum(0));
  cumulativeProfit.splice(0,0);
  cumulativeProfit.pop();


  for (let i = 0; i < peopleInLine.length; i++) {
      if (peopleInLine[i] === 25) { changeRequired.push(0) }
      else if (peopleInLine[i] === 50) { changeRequired.push(25) }
      else if (peopleInLine[i] === 100) { changeRequired.push(75) }
  };


  let cumulativeOutgoings = changeRequired.map(cumulativeSum(0));
  cumulativeOutgoings.splice(0,0);
  cumulativeOutgoings.pop();
  return cumulativeOutgoings;
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。