当前位置: 首页 > 知识库问答 >
问题:

这个JavaScript foo()中发生了什么;功能?[重复]

宇文温文
2023-03-14

嘿,我不能正确理解这个JavaScript代码:

 foo(i) {
     if (i < 0)
         return;

     console.log('begin: ' + i);

     foo(i - 1);
     console.log('after: ' + i);
 }

 foo(3);

输出

begin: 3
begin: 2
begin: 1
begin: 0
after: 0
after: 1 
after: 2
after: 3

所以我知道前四个输出的代码内部发生了什么,但无法理解最后四个输出的代码内部发生了什么,请有人详细解释最后四个输出的代码,这将对我真正有帮助。

共有1个答案

阎德义
2023-03-14

所以这个例子显示了递归函数调用,因为它执行:

 function foo(i)
  {
    if(i<0)
    return;
    console.log('begin: ' +i); // Line 1
    foo(i-1);  // Line 2
    console.log('after: ' +i);  // Line 3
  }
  foo(3);

发生的情况是,首先调用第 1 行,然后在第 2 行再次调用该函数,然后调用第 3 行

所以执行堆栈看起来像这样

console.log('begin: ' +3); // Line 1
foo(2);  // Line 2
console.log('after: ' +3);  // Line 3

现在,下一行2将再次转换为:

console.log('begin: ' +3); // Line 1
console.log('begin: ' +2); // Line 1
foo(1); // Line 2
console.log('after: ' +2);  // Line 3

console.log('after: ' +3);  // Line 3

等等

console.log('begin: ' +3); // Line 1
console.log('begin: ' +2); // Line 1
console.log('begin: ' +1); // Line 1
foo(0); // Line 2
console.log('after: ' +1);  // Line 3
console.log('after: ' +2);  // Line 3

console.log('after: ' +3);  // Line 3

和最终迭代:

console.log('begin: ' +3); // Line 1
console.log('begin: ' +2); // Line 1
console.log('begin: ' +1); // Line 1
console.log('begin: ' +0); // Line 1
foo(-1) // Line 2 for negative value, we are exiting the recursion.
console.log('after: ' +0);  // Line 3
console.log('after: ' +1);  // Line 3
console.log('after: ' +2);  // Line 3

console.log('after: ' +3);  // Line 3
 类似资料:
  • 我们最近在大学里做了一个关于几种语言的编程专题的讲座。 讲师写下了以下功能: 虽然我完全理解就可读性而言这也是非常糟糕的风格,但他的主要观点是,这部分代码在生产代码中工作得很好,直到它们实现了高优化级别。然后,代码将什么也不做。 他说所有对变量< code>tmp的赋值都会被编译器优化掉。但是为什么会这样呢? 我知道在某些情况下,变量需要声明为易失性,以便编译器不会触及它们,即使他认为它们从未被读

  • 我刚刚浏览了一些关于如何在另一个像素阵列之上绘制像素阵列的代码,如下所示: } 如您所见,一个人能够在另一个位图之上的特定坐标上绘制一个位图对象。 我不明白的是两个for循环。我知道,外部for循环是绘制位图的y轴,并启动内部for循环来绘制位图的x轴。 现在我过来了: sp和dp到底代表什么?'c'在后面是什么意思 ? 提前感谢,致以最诚挚的问候

  • 我写了一个函数: 我想的是用一个“cur”来记录这两个链表“a”和“b”中的每个节点。然后这两个链表'a'和'b'移动到它的下一个节点。然后转到下一个WHILE循环。 然而,这是错误的。当我调试时,在这个第一个WHILE循环中,当它完成这个

  • 问题内容: 早期的javadoc 这样表示有一个接口,它似乎有一个同样的关系作为必须的。 现在看来,我们固守在,这肯定是不一样的。 发生了什么事? 问题答案: 它已被删除前一段时间。布赖恩·格茨(Brian Goetz)提出了撤职的理由: 当前,唯一的实现者是Collection,所有其他支持流的方法都使用一种比“ stream”更合适的方法名称来提供特殊的流(chars(),codePoints

  • 问题内容: 它是在beta中,但不是在发布中? 问题答案: 对于后备甚至更好的是:

  • 问题内容: 编码 我有以下瞬态模型: 如您所见,它们都是通过1:N关系连接的。我以这种方式打开瞬态模型的视图: 我的目的 在模型的方法中,我想访问其相关的管理器(及其字段)。 预期的行为 假设我刚刚创建的ID为11。 当前行为 我的问题 我知道瞬态模型不是永久存储的,而是根据数据库的系统参数在一段时间后被删除的。但是,当它们在数据库中时,它们确实具有ID。实际上,当我打开瞬态模型表单(激活了开发人