代码之家  ›  专栏  ›  技术社区  ›  3gwebtrain

这个函数如何处理没有循环的数组?

  •  0
  • 3gwebtrain  · 技术社区  · 6 年前

    这是我的示例函数。

        let array = ["x", "y", "z", 4, 5];
        
        function print(arr, pos, len) {
          if (pos < len) {
            console.log(arr[pos]);
            print(arr, pos + 1, len);
          }
          return;
        }
        print(array, 0, array.length);

    数组逐个打印。但是如果没有循环,这是怎么发生的呢?有人澄清了解这里的功能流程吗?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Nick Parsons Felix Kling    6 年前

    没有循环怎么会这样?

    它正在使用 recursion 这意味着函数本身是从函数内部调用的。使用循环不是迭代集合的唯一方法。

    如果你看你的代码 print 函数在函数外部调用一次,也在函数内部调用一次。 打印 函数本身。所以当我们第一次用数组运行函数时 [1, 2, 3] 我们使用以下参数运行函数:

    print([1, 2, 3], 0, 3)

    当我们进入函数时,我们会看到 if 陈述并看到 pos (0)实际上小于 len (3)。所以,我们继续 console.log(arr[0]) 它将打印数组中的第一项。

    然后我们转到下一行,然后打电话 打印 再一次,但这次是从函数内部进行的。我们现在用以下参数来调用它:

    print([1, 2, 3], 1, 3)

    这个,再过一遍,看看 如果 语句,确保它是正确的,然后运行 console.log(arr[1]) 再说一遍,我会打电话 打印 使用以下参数:

    print([1, 2, 3], 2, 3)

    那么这个就可以了 console.log(arr[2]) (数组中的最后一项)然后再次调用 打印 使用以下参数:

    print([1, 2, 3], 3, 3) 然而,这次,我们 如果 语句不满足/不正确 销售时点情报系统 (3)不小于 伦恩 (3)。换句话说,我们的 基本情况 (停止递归的条件)已满足。所以,我们要做的不是打印 return .

    做某事 返回 会带我们回到上次打电话的地方 打印 声明,这意味着我们将回到 如果 上一次调用的语句 打印 然后 返回 再一次 如果 语句已完成。这个瓦解的过程一直持续到我们 返回 我们最初的呼叫 打印 . 然后,我们的程序在此之后终止,因为没有更多的代码可以运行。

        2
  •  1
  •   Akrion    6 年前

    在这个过程中 函数调用自身 直接或间接是 调用递归,相应的函数作为递归调用 功能

    在您的场景中,这意味着 print 从函数体内部多次调用以打印数组内容。

    let array = ["x", "y", "z", 4, 5];
    
    function print(arr, pos, len) { // <-- notice current position is passed as parameter
      if (pos < len) {              // <-- keep doing it until end of the array
        console.log(arr[pos]);      // <-- prints to the console the value at current position
        print(arr, pos + 1, len);   // <-- print function is called again with dif. pos!
      }
      return;
    }
    print(array, 0, array.length);  // <-- call the print function with 0 and 5 as parameters
    
        3
  •  0
  •   Sachin Sarola    6 年前

    它是一个递归函数:

    阅读博客,简单而有效: click Here