javascript - How to learn recursion?
漂亮男人
漂亮男人 2017-07-05 10:51:50
0
6
859

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

漂亮男人
漂亮男人

reply all(6)
三叔

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.

大家讲道理

The simple understanding is: the function calls itself.

Qualified recursion must have an ending condition.

Understand these 2 points and you’ll be fine.

我想大声告诉你
  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)
三叔

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.

Peter_Zhu
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
曾经蜡笔没有小新

Experience of an experienced driver: practice more and learn more

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template