我想解决问题(来自https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register/)。 我最终在reduce方法中使用了switch语句,但是它不能像我在代码中解释的那样工作。 我只是想知道为什么这行不通,如果没有其他更好的方法来解决整个问题,那么我就是不知道。
function checkCashRegister(price, cash, cid) {
// price refer to a purchase price, cash to the money given by a client, cid to the cash-in-drawer.
// With the method below, I want to convert the cid nested array into a single value in dollar.
let register = cid.reduce( (sum, curr) => {
switch (curr[0]) {
case "PENNY" :
sum += curr[1] * 0.01;
break;
// I would continue with case "NICKEL" etc. but the switch statement doesn't work.
default: console.log("Unexpected currency unit");
}
},0)
console.log(register);
}
checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);
我希望输出为0.0101,但“ console.log(register)”的实际输出为:
Unexpected currency unit
Unexpected currency unit
Unexpected currency unit
Unexpected currency unit
Unexpected currency unit
Unexpected currency unit
Unexpected currency unit
Unexpected currency unit
答案 0 :(得分:0)
Array.reduce要求您返回一个值。您的切换语句很好。我在您的reduce函数的末尾添加了return sum;
。
function checkCashRegister(price, cash, cid) {
// price refer to a purchase price, cash to the money given by a client, cid to the cash-in-drawer.
// With the method below, I want to convert the cid nested array into a single value in dollar.
let register = cid.reduce( (sum, curr) => {
switch (curr[0]) {
case "PENNY" :
sum += curr[1] * 0.01;
break;
// I would continue with case "NICKEL" etc. but the switch statement doesn't work.
default: console.log("Unexpected currency unit");
}
return sum;
},0)
console.log(register);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
您确实需要做一些工作才能回答您链接的问题,但是我敢肯定您会到达那里。祝你好运。