简体   繁体   中英

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:

[
Textnode {"Some Text"}
]

The upper code is valid HTML, actually it is a text node. 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:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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