繁体   English   中英

了解递归函数

[英]Understanding the recursive function

也许这个功能对您来说很简单。 但是我对该函数的工作方式有疑问。请解释如何编译此函数。

运行循环中的计数为零吗?

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

DOM将如下所示:

[
Textnode {"Some Text"}
]

上面的代码是有效的HTML,实际上是一个文本节点。 因此,如果要获取其长度,我们只需考虑其长度即可:

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

让我们想象一个更复杂的情况:

Some Text <span> nested </span>

DOM:

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

现在我们有了四个节点。 文本节点和跨度节点,以及嵌套在该跨度节点中的文本节点。 它们都嵌套在某种身体中。 因此,要获取其文本长度,我们需要遍历节点,然后再深入了解(看看树的遍历 ):

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

因此上例将如下所示:

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