javascript - 递归程序打印数字的问题
问题描述
我在下面的程序中有问题,下面的程序打印数字从 1 到 9,但我也想打印数字 10,我该怎么做?
function a(n){
if(n == 1){
return;
}
a(--n);
console.log("hello world = ",n);
}
a(10);
解决方案
只有当您的数字不为零时,您才需要切换退出条件并调用该函数。
function a(n) {
if (n !== 1) a(n - 1);
console.log("hello world =", n);
}
a(10);
你所拥有的是
function a(n){
if (n == 1) { // exit condition
return; // end of function run
}
a(--n); // mutating variable
console.log("hello world = ", n);
}
检查值并结束函数的退出条件。这可以防止打印最后一个值。
另一个问题是n
再次调用该函数的失败。后来使用的变量不再具有原始值。
通过将退出函数更改为检查是否应该再次调用该函数,与退出相反,它允许为每个想要的数字运行并进行输出。
如果您只是将 更改--n
为n - 1
,则需要另一个输出1
。
function a(n){
if (n == 1) {
console.log("hello world = ", n); // add another output here for 1
return;
}
a(n - 1);
console.log("hello world = ", n);
}
a(10);
推荐阅读
- java - 在java中将服务注入DAO的好方法吗
- php - 根据用户在同一页面登录两次来更改 HTML 内容
- docker - 在 Grafana 中查看 Docker CPU 使用情况——jiffies?
- java - 多个 Spring Boot 错误:包 org.springframework.boot 不存在
- javascript - 如何得到这个脚本的结果?
- android - 从 finally 子句调用 AttributeSet.recycle() 是 Android 反模式吗?
- reactjs - 浏览器忽略缓存头并在 React 应用程序部署后寻找旧的 CSS 和 JavaScript 文件
- apache-spark - 从 Ignite 加载 Spark 数据帧时出现 NoSuchMethodError
- django - 如何过滤 get_context_data 中的数据
- php - PHP:带有和不带有变量的错误 URI