0

i'm having trouble understanding where my logic fails! When I try to impose a word.length condition on pushing the word i've got from a paragraph in an array, i get stuck in an infinite loop. Please let me know your thoughts, thanks to all!

var str = document.getElementsByTagName('p')[0].innerHTML;
console.log(str);



function wordIndexes(str) {
    var result = [];
    var len = str.length;
    var i = 0, j, word;

    while (i < len) {
        if (str[i] === ' ') {
            ++i;
        }
        else {
            word = "";
            for (j = i; j < len && str[j] !== ' '; ++j) {
                word += str[j];
            }

              console.log(word.length);

            //imposing length conditions
              if (word.length < 4)
               {console.log('too short')}

              else {    
              result.push([i, word]);
              i = j;
              };


        }
    }
    return result;  
}
8
  • 1
    it should be i++ not ++i i think Commented Jul 11, 2013 at 7:26
  • Could you explain in words what are you trying to achieve here? Commented Jul 11, 2013 at 7:28
  • and add some HTML code. Commented Jul 11, 2013 at 7:29
  • Create a jsfiddle for this and post the link.... include data so people can play with it. jsfiddle.net Commented Jul 11, 2013 at 7:30
  • 2
    @GintasK in this code i is not part of an expression, so pre-incrementing it or post-incrementing it doesn't matter. Commented Jul 11, 2013 at 7:32

3 Answers 3

3

If the word length is less than 4 your code logs a message, but doesn't update i, so the next iteration starts at the same point, and fails at the same point.

I'd suggest an alternative but it's not clear how you intend to handle this condition.

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

1 Comment

Hello mike many thanks for your answer, it was indeed the problem, and it now works
0
if (word.length < 4)
{
  console.log('too short')
}
else
{
  ...

If you go in this condition, the i counter doesn't change. Check you don't go in this condition everytime

1 Comment

Thank you Ric you were right also, i forgot to update to i counter. Its all fixed now!
0

You missed i =j in your if statement

if (word.length < 4)
{
  console.log('too short')

i = j  // You missed this

}

Comments

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.