简体   繁体   中英

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

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

 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 ));

Because in the last call where num = 0 you are trying to access arr[num-1] which is arr[0-1] => arr[-1] = undefined . Hence all the result becomes NaN.

You need to write the method in following way,

 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 ));

Or,

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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