给定金额

时间:2018-06-06 23:11:34

标签: javascript jquery

我正在尝试在javascript / jquery中创建一个函数,以计算出总投入金额所需的最小硬币数量。

所以我有一个硬币的对象数组:

var coins = [
    {
        pennies: 200, 
        print: '£2'
    }, 
    {
        pennies: 100, 
        print: '£1'
    }, 
    {
        pennies: 50, 
        print: '50p'
    }, 
    {
        pennies: 20, 
        print: '20p'}, 
    {
        pennies: 10,
        print: '10p'
    }, 
    {
        pennies: 5, 
        print: '5p'}, 
    {
        pennies: 2, 
        print: '2p'
    },
    {
        pennies: 1, 
        print: '1p'
    }
];
var $input = $('input');
$input.keypress(function(e) {
    if (e.which == 13) {
        // do something
    }
});

我的HTML中的输入字段。

因此,如果有人输入123p,我希望表单返回1 x£1,1 x 20p,1 x 2p和1 x 1p。

我正在努力弄清楚从哪里开始。如果有人能提供帮助,我将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

听起来你只需要从最高面额开始迭代coins数组:



const coins=[{pennies:200,print:'£2'},{pennies:100,print:'£1'},{pennies:50,print:'50p'},{pennies:20,print:'20p'},{pennies:10,print:'10p'},{pennies:5,print:'5p'},{pennies:2,print:'2p'},{pennies:1,print:'1p'}];

const getCoins = penniesToGo => coins.reduce((coinCountStr, { pennies, print }) => {
  const numCoins = Math.floor(penniesToGo / pennies);
  if (numCoins < 1) return coinCountStr;
  penniesToGo -= numCoins * pennies;
  const thisCoinStr = `${numCoins}x ${print}`;
  return coinCountStr ? coinCountStr + ', ' + thisCoinStr : thisCoinStr;
}, '');

console.log(getCoins(201));
console.log(getCoins(333));
console.log(getCoins(6));
&#13;
&#13;
&#13;