什么是递归?什么时候有用?

递归是过程的重复应用。在JavaScript中,递归涉及重复调用自己的函数,直到达到基本条件为止。基本条件脱离了递归循环,因为否则该函数将无限期地调用自身。当使用包含嵌套(深度级别未知)的数据结构时,递归非常有用。

例如,您可能有一个从数据库返回的注释线程,这些注释存在于平面数组中,但需要嵌套才能在UI中显示。每个评论要么是顶级评论(无父),要么是对父评论的回复。评论可以是回复的回复……我们事先不知道评论的层次数。这是递归可以提供帮助的地方。

const nest = (items, id = null, link = "parent_id") =>
  items
    .filter(item => item[link] === id)
    .map(item => ({ ...item, children: nest(items, item.id) }))

const comments = [
  { id: 1, parent_id: null, text: "首先回复发布。" },
  { id: 2, parent_id: 1, text: "First reply to comment #1." },
  { id: 3, parent_id: 1, text: "Second reply to comment #1." },
  { id: 4, parent_id: 3, text: "First reply to comment #3." },
  { id: 5, parent_id: 4, text: "First reply to comment #4." },
  { id: 6, parent_id: null, text: "第二次回复发帖。" }
]

nest(comments)
/*
[
  { id: 1, parent_id: null, text: "首先回复发布。", children: [...] },
  { id: 6, parent_id: null, text: "第二次回复发帖。", children: [] }
]
*/

在上面的示例中,如果filter() 返回空数组,则满足基本条件 。链式 map() 将不会调用包含递归调用的回调函数,从而中断循环。

很高兴听到

  • 当使用包含未知数量的嵌套结构的数据结构时,递归非常有用。

  • 递归必须满足一个打破循环的基本条件,否则它将无限期地调用自身。