2017-07-22 28 views
1

多分、この関数はあなたにとって非常に簡単です。しかし、私はこの関数の動作方法に問題があります。この関数をコンパイルする方法を説明してください。再帰関数の理解

実行ループのカウントはゼロですか?

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

数はconsole.logの中間にを入れて、いくつかの追加デバッガのブレークポイントを取得し、簡単な例を実行して実行し、実際に複雑ではないことを確認します。 –

+1

これを単語に変換するだけです。現在のノードがテキストノードの場合は長さを返し、そうでない場合はその子をループし、関数を(すべての子に対して)再度呼び出して結果を合計します。結果を返します。 –

+0

ツリーの* leaf *ノードに格納されているすべてのテキストの合計長を数えます。 – meowgoesthedog

答えて

0
Some Text 

DOMは次のようになります。

[ 
Textnode {"Some Text"} 
] 

上部のコードは、実際にそれがテキストノードで、有効なHTMLです。私たちはその長さを取得したいのであれば、私たちは単にその長さを取る:

Some Text <span> nested </span> 

はDOM::

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

今weveは、4つのノードを持って

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

は、より複雑なケースを想像します。テキストノードとスパンノード、およびスパンノードにネストされたテキストノード。そして彼らはすべて何らかの体の中に入れ子になっています。だから、そのテキストの長さを得るために、我々はノードを反復処理する必要があり、その後、より深く行く(ツリートラバーサルに見て):

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