0

I have a JavaScript function as:

function nodeExists(text, ancestor, tree, generationCount) {

tree.findByText(text).each(function (index, element) {

    var gen = generationCount;
    var currNode = element;
    while (gen !== 1) { // 1: node itself

        currNode = tree.parent(currNode);
        gen--;
    }

    if (tree.text(currNode) === ancestor)
        return currNode; // Even if condition is met, control continues looping       
})       

return null;
//return ($.inArray(ancestor, gArr) !== -1) ? true : false;
}

While debugging function not exiting from a loop even if tree.text(currNode) === ancestor is truthy. Is Jquery .each causing it. Please help me.

6
  • First question, what's being passed for generationCount? I would also suggest that you don't do while (gen !== 1) but instead, while (gen > 1), just in case something goes wrong. Commented Sep 19, 2013 at 11:51
  • Only returning false will stop the iteration with each, use break or return false so element == currNode Commented Sep 19, 2013 at 11:52
  • Down-vote is OK for immature question. Commented Sep 19, 2013 at 14:06
  • @Scott generationCount is integer > 1. While while(gen > 1) works good, what is its benefit over while(gen !== 1), some kind of cuteness or performance reasons? Commented Sep 19, 2013 at 14:33
  • @Binbsr: The advantage is that if this is somehow called with a bad value of generationCount, such as 0 or -73, or "abc", the code won't get stuck in an infinite loop. Commented Sep 19, 2013 at 17:13

3 Answers 3

6

From the jQuery documentation:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

You aren't returning false so the loop will continue.

Sign up to request clarification or add additional context in comments.

Comments

0

Did you try an alert instead of a return ? Perhaps your ancestor is not "===" but just "==" to your tree.text(currNode) ?

1 Comment

I don't need alerts, since i am debugging it line by line :). And === is deliberate, since it is fast (don't need type conversions) than ==. Thanks anyway.
0

You will have to return 'false'. Otherwise, it will go to next iteration.

1 Comment

Thanks, i already accepted the answer for nice advice, i can't vote you up (Sorry to my reputation score).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.