簡體   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