繁体   English   中英

当我用 --> multiply( [ 1, 2, 3, 4, 5 ], 3 ) 调用这个递归 function 时,我得到 NaN。 背后的原因是什么?

[英]When I call this recursive function with --> multiply( [ 1 , 2 , 3 , 4 , 5 ] , 3 ) , I get NaN. What is the reason behind?

当我用 --> multiply( [ 1, 2, 3, 4, 5 ], 3 ) 调用这个递归 function 时,我得到 NaN。 背后的原因是什么?

 let multiply = function (arr, num) { if (num <= 0) { return 1; } return arr[num - 1] * multiply([1, 2, 3, 4, 5], num - 1); } console.log(multiply( [ 1, 2, 3, 4, 5 ], 3 ));

因为在最后一次调用 where num = 0时,您试图访问arr[num-1] ,即arr[0-1] => arr[-1] = undefined 因此,所有结果都变为 NaN。

您需要按以下方式编写方法,

 let multiply = function (arr, num) { if (num < 0) { return 1; } return arr[num] * multiply([1, 2, 3, 4], num - 1); } console.log(multiply( [ 1, 2, 3, 4, 5 ], 3 ));

或者,

 let multiply = function (arr, num) { if (num < 1) { return 1; } return arr[num - 1] * multiply([1, 2, 3, 4], num - 1); } console.log(multiply( [ 1, 2, 3, 4, 5 ], 4 )); // In this case you have add +1 to the num you want because we are never using arr[num] for the first call.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM