【发布时间】:2018-03-11 23:04:24
【问题描述】:
所以,我坚持使用这段代码几个小时。
function amountTocoins(amount, coins) {
if (amount === 0) {
return [];
} else {
if (amount >= coins[0]) {
left = (amount - coins[0]);
return [coins[0]].concat( amountTocoins(left, coins));
} else {
coins.shift();
return amountToCoins(amount, coins);
}
}
}
document.write(amountTocoins(46, [25, 10, 5, 2, 1])); /25, 10, 10, 1
据我所知,这里的数量是46,硬币是25、10、5、2、1,所以接下来,数量大于或等于硬币,下一块:
left = (amount - coins[0]);
基本上是 25(零索引),下一个;
return [coins[0]].concat( amountTocoins(left, coins));
concat() 方法用于合并两个或多个数组,但是在这个特定的代码中是如何合并的呢?输出为:25、10、10、1,我在上面的代码中也注释了。
我希望我能很好地描述我的问题
【问题讨论】:
-
首先金额是 43 而不是 46 ;)
-
好的,太好了....
标签: javascript arrays function concat