简体   繁体   English

如何使用具有 JavaScript 约束的 function 查找阶乘

[英]How to find factorial using a function with constraints in JavaScript

I am trying to find the factorial of an integer using a function with the following constraint我正在尝试使用具有以下约束的 function 找到 integer 的阶乘

1<=N<=10 1<=N<=10

Below is my code but when I execute it I am receiving NaN.下面是我的代码,但是当我执行它时,我收到了 NaN。 Can you please explain and show me where is my mistake.你能解释一下并告诉我我的错误在哪里吗? Much appreciated!非常感激!

 const factorial = function (n) { if (n >= 1 && n <= 10) { return n * factorial(n - 1); } }; console.log(factorial(5));

Try to follow your code step by step and you will find the issue quite easily.尝试一步一步地遵循您的代码,您会很容易发现问题。

When you don't return anything and you tried to access the returned value you get undefined.当您不返回任何内容并尝试访问返回的值时,您会得到未定义的值。

Imagine your type factorial(3)想象一下你的类型factorial(3)

Your code will run 3 * 2 * undefined您的代码将运行 3 * 2 * undefined

You need to return 1 when n = 1.当 n = 1 时,您需要返回 1。

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

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