【问题标题】:Javascript help w/exerciseJavascript 帮助/练习
【发布时间】: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


【解决方案1】:

您在这里处理的术语是recursion - 当函数在其体内调用自身时的一种现象。您在两个地方(第 6 行和第 9 行)在自身内部调用 amountTocoins 函数。

在你的行中:

return [coins[0]].concat( amountTocoins(left, coins));

连接会暂停,直到对amountTocoins 函数的新调用被执行并返回值。在您的示例中,您的行被解释为:

return [25].concat(amountTocoins(21, [25, 10, 5, 2, 1]))

在您执行amountTocoins(21, [25, 10, 5, 1, 2]) 之前,您的[25].concat(..) 函数不会执行。

您会越来越深入,直到到达停止此嵌套函数调用(递归)的底线条件。在您的情况下,条件是amount === 0,它将返回您将连接的第一个值,即空数组[]

注意:您在上一次 amountTocoins 函数调用(第 9 行)中有错字。

【讨论】:

  • 对,我实际上听说过“递归”。无论如何,谢谢你:)
猜你喜欢
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 2018-09-15
  • 2017-11-28
  • 1970-01-01
  • 2011-09-21
相关资源
最近更新 更多