理解递归函数

时间:2017-07-22 10:33:07

标签: javascript recursion

也许这个功能对你来说非常简单。但我对这个函数的工作原理有疑问。请解释如何编译这个函数。

运行循环中的计数为零?

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;
}

2 个答案:

答案 0 :(得分:0)

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"}
  ]
 }
]

现在我们有四个节点。文本节点和span节点,以及嵌套在span节点中的文本节点。而且它们都嵌套在某种身体里。因此,要获得文本长度,我们需要遍历节点,然后更深入(查看树遍历):

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

答案 1 :(得分:0)

/**
** 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;
}

enter image description here