简体   繁体   English

了解递归函数

[英]Understanding the recursive function

Maybe this function is very simple for you. 也许这个功能对您来说很简单。 but i have problems with how this functions works.please explain how to compile this function. 但是我对该函数的工作方式有疑问。请解释如何编译此函数。

It is zero the count in the run loop ? 运行循环中的计数为零吗?

function countChars(elm) {
  var i, count = 0;

  if (elm.nodeType == 3) { // TEXT_NODE
    return elm.nodeValue.length;
  }

  for (i = 0, child; child = elm.childNodes[i]; i++) {
    count += countChars(child);
  }
  return count;
}
Some Text

The DOM will look like this: DOM将如下所示:

[
Textnode {"Some Text"}
]

The upper code is valid HTML, actually it is a text node. 上面的代码是有效的HTML,实际上是一个文本节点。 So if we want to get its length we simply take its length: 因此,如果要获取其长度,我们只需考虑其长度即可:

if (elm.nodeType == 3) { // TEXT_NODE
   return elm.nodeValue.length;
}

Lets imagine a more complicated case: 让我们想象一个更复杂的情况:

Some Text <span> nested </span>

DOM: DOM:

[
Textnode {"Some Text"},
Span { 
  children:[
    Textnode {"nested"}
  ]
 }
]

Now weve got four nodes. 现在我们有了四个节点。 A text node and a span node, and a text node nested in the span node. 文本节点和跨度节点,以及嵌套在该跨度节点中的文本节点。 And theyre all nested in some kind of body. 它们都嵌套在某种身体中。 So to get its text length, we need to iterate over the nodes, and then go deeper ( have a look into tree traversal ): 因此,要获取其文本长度,我们需要遍历节点,然后再深入了解(看看树的遍历 ):

var count = 0;
for (var i = 0, child; child = elm.childNodes[i]; i++) {
  count += countChars(child);
}
return count;

So the upper example will work like this: 因此上例将如下所示:

count=0
iterate over body:
  child textnode:
      count+="Some Text".length
  child span:
      inner count=0
      iterate over span:
          child textnode
               inner count+="nested".length
     count+=inner count
finished
/**
** This function counts the characters of a given node.
**
** @param : The current node to work on
**/
function countChars(elm) {

  // Set local variables
  var i, count = 0;

  // Check to see if the current node is text.
  // If its a text it cannot have any other children so simply
  // return the text length int his node
  if (elm.nodeType == 3) { // TEXT_NODE
    return elm.nodeValue.length;
  }

  // This is not a text node so driil doen in to its all
  // children and loop into them to count the number of 
  // character they have
  for (i = 0, child; child = elm.childNodes[i]; i++) {
    // dive into the current child in count the number of 
    // characters it contains. since we use recursion the count will 
    // be returned form the previous run and will return the number of
    // characters collect from all "previous" children

    count += countChars(child);
  }

  return count;
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM