问题描述
我是一个初学者,正在尝试一些关于 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;
};