javascript - 解释这个 JavaScript 递归
问题描述
解释一下这个 JavaScript 递归,当 0<0 表达式对 foo(3) 进行 eval 时究竟会发生什么?
function-foo return console.log("test")
是不是在return语句中传递的console.log()异常?
是否该数组对于索引 3 和 4 有两个 0,因为 foo 评估 0 两次,因为一旦 i-1 达到 1-1 递归调用应该是 foo(0) 是的?
但是继续,但是 console.log 被调用了两次,其中 foo() 递归调用在两者之间被提升了 order 在这里有什么区别?
我不明白为什么这些是结果
let ar = [];
function foo(i) {
if (i < 0)
return console.log("test");
ar.push(i);
console.log(i, Boolean(i<0));
foo(i - 1);
ar.push(i);
console.log(i, Boolean(i<0));
}
foo(3)
console.log('ar=', JSON.stringify( ar ))
.as-console-wrapper { max-height: 100% !important; top: 0 }
解决方案
你做的递归代码foo(3)
:
function foo(i) {
if (i < 0) return // stop recursive call
ar.push(i) // first push
foo(i - 1) // recursive call
ar.push(i) // second push
}
ar.push(3) // ar = [3] ==== firsts push
ar.push(2) // ar = [3,2]
ar.push(1) // ar = [3,2,1]
ar.push(0) // ar = [3,2,1,0]
return // i == -1 , (i<0) is true => no pushS, no foo(i - 1)
ar.push(0) // ar = [3,2,1,0,0] === seconds push
ar.push(1) // ar = [3,2,1,0,0,1]
ar.push(2) // ar = [3,2,1,0,0,1,2]
ar.push(3) // ar = [3,2,1,0,0,1,2,3]
推荐阅读
- python - 如何对两个以上的类别进行空间情绪分析
- node.js - 按电话号码跟踪链接点击次数
- image - 如何在反应本机应用程序中通过相机(反应本机图像选择器)捕获和渲染多个图像
- javascript - 如何在 Spring MVC 的 JSP 登录页面中实现记住我?
- javascript - @keyup.delete输入直到为空时如何触发功能?VueJS
- django - 即使级别设置为 ERROR,Django 记录器的级别也不会跟踪 INFO 消息
- javascript - 无法在 VAST - FLUID PLAYER 中显示“跳过广告”
- node.js - 如何在通过 sql 查询保存数据或更新数据时删除脚本注入?
- entity-framework - EF Core 不能在父级中包含子级
- javascript - NodeJS:从 readStream 获取文件名