Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按给定的货币数组计算更改_Javascript_Arrays - Fatal编程技术网

Javascript 按给定的货币数组计算更改

Javascript 按给定的货币数组计算更改,javascript,arrays,Javascript,Arrays,这是我需要解决的问题,我有任何产品的价格,例如5枚硬币,我需要给客户零钱,例如5枚硬币,我有可能的货币数组,我可以用来给零钱[1,2,5,10,20,50100]这是我的代码 const currency=[1,2,5,10,20,50,100]; const getChange=(amountancents)=>{ 返回货币.reverse().map(硬币=>{ 让amountCoin=数学地板(amountcents/coin); 数量-=数量硬币*硬币; 退币 }).reverse()

这是我需要解决的问题,我有任何产品的价格,例如5枚硬币,我需要给客户零钱,例如5枚硬币,我有可能的货币数组,我可以用来给零钱[1,2,5,10,20,50100]这是我的代码

const currency=[1,2,5,10,20,50,100];
const getChange=(amountancents)=>{
返回货币.reverse().map(硬币=>{
让amountCoin=数学地板(amountcents/coin);
数量-=数量硬币*硬币;
退币
}).reverse()
};
console.log(getChange(5));

//返回[0,0,1,0,0,0,0,0]
使用
reduce
方法将数组中的所有数字相加

这会给你硬币的数量

 result.reduce((allCoins, numberOfDenomination) => allCoins += numberOfDenomination);
const currency=[1,2,5,10,20,50,100];
const getChange=(amountancents)=>{
返回货币.reverse().map(硬币=>{
让amountCoin=数学地板(amountcents/coin);
数量-=数量硬币*硬币;
退币
}).reverse()
};
console.log(
getChange(5).减少((硬币,n)=>硬币+=n)

);这是一个著名的问题。我想有很多解决办法。我的解决方案是递归的。(这不一定是高效的,很多时间都是如此)

const currency=[1,2,5,10,20,50,100];
const\u getChange=(金额、货币、结果)=>{
如果(amountancents<0 | | currency.length==0){
返回[]
}else if(amountancents==0){
返回结果
}否则{
newArr=result.map(e=>[…e,货币[0]]
return _getChange(amountancents-currency[0],currency,newArr).concat(_getChange(amountancents,currency.slice(1),result))
}  
};
const getChange=(金额、货币)=>{
return _getChange(金额、币种、[[]]
}

log(getChange(5,currency))
您是否只想获取所有类型硬币的数量?或者将要返还的硬币类型?获取所有可能类型的硬币数量您请求的结果与此算法的要求Deckout没有太大关系。这看起来符合我的要求,但代码返回了许多可能的方法,太好了,它返回的方式不是很多,而是像这样,让它是5,返回数组,像[11111,221,1112,5]非常感谢,马赫,这就是我想要做的