search

Home  >  Q&A  >  body text

javascript - How to learn recursion?

It’s hard to understand. Do you have any suggestions?

漂亮男人漂亮男人2691 days ago840

reply all(6)I'll reply

  • 三叔

    三叔2017-07-05 10:53:50

    Look at my previous answer to a recursion question. Understanding recursion in terms of function implementation
    I don’t know if it will be helpful to you.

    reply
    0
  • 大家讲道理

    大家讲道理2017-07-05 10:53:50

    The simple understanding is: the function calls itself.

    Qualified recursion must have an ending condition.

    Understand these 2 points and you’ll be fine.

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-07-05 10:53:50

    1. If you want to learn recursion, you must first learn recursion.

    2. Recursion is the stuffing of steamed buns, and the limit is steamed buns.

    3. Gives a normal code example:

    Suppose we want to traverse a [nested] data structure, such as [the children attribute of a DOM element or a DOM element of the same type], then the simplest and most common recursion will be used: the function calls itself, layer by layer Unnesting only requires one or two lines of JS:

    function walk (node) {
      // 先打印出本节点的值
      console.log(node.value)
      // 对每个 child 调用自身
      node.children.forEach(child => walk(chid))
    }
    
    // 简单的树形嵌套数据结构示例
    const tree = {
      value: 1,
      children: [
        { value: 2, children: [] },
        { value: 3, children: [{ value: 4, chilren: [] }] },
        { value: 5, children: [] }
      ]
    }
    // 遍历该树形数据结构
    walk(tree)

    reply
    0
  • 三叔

    三叔2017-07-05 10:53:50

    Recursion is actually not difficult to understand. Let me give you an example. There are apples on only one floor of a 6-story building. If we find apples on any floor, we will stop. . There will be two results when searching once. You don’t need to search down to make a judgment. Searching down means repeating the first process. This is recursion.

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 10:53:50

    int i;
    int function a(i){
        if (i < 2) return a(i+1);
        else return i;
    }
    a(0);    //执行后返回2

    The above code is easy to understand without writing standards. Recursion means calling itself to form a nest.
    Because there is only one return statement, so after calling a(0) we can see it like this:
    Nested in:

    a(0)->a(a(0+1))->a(a(1))
    a(a(a(1+1)))->a(a(a(2)))

    Coming back:

    a(a(a(2)))->a(a(2))
    a(a(2))->a(2)
    a(2)->2
    

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:53:50

    Experience of an experienced driver: practice more and learn more

    reply
    0
  • Cancelreply