Javascript 如何在reduce方法中使用switch语句?

Javascript 如何在reduce方法中使用switch语句?,javascript,Javascript,我想从中解决一个问题。 我在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 th

我想从中解决一个问题。 我在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.logregister的实际输出为:

    Unexpected currency unit
    Unexpected currency unit
    Unexpected currency unit
    Unexpected currency unit
    Unexpected currency unit
    Unexpected currency unit
    Unexpected currency unit
    Unexpected currency unit

Array.reduce要求您返回一个值。你的开关状态很好。我加上了回报金额;到reduce函数的末尾

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);
} 

为了回答你链接的问题,你确实有一些工作要做,但我相信你会做到的。祝你好运。

你从你的reduce回调中永远不会返回任何东西。所以,万一佩妮什么也没发生。你需要在reduce函数中返回一些东西首先,你需要从最大的单位迭代到最小的单位,在这种情况下reduceRight是合适的。然后你需要取这个值,它是面值的和,而不是它的计数。thant的意思是,您不需要switch语句,但需要检查金额是否足以获得该单位的更改。然而,你始终没有达到想要的结果。它是一个带有面额和总和的数组吗?还是剩下的现金?@VLAZ谢谢你的评论!很抱歉你因为我的错误耽误了时间…我应该编辑我的问题来改进吗?谢谢你的回答。这很有效。我知道我可能犯了一个可笑的错误,但我真的很感激你的宽容。