4

While working on a syntax highlighter that runs on JQuery, I have found a rather odd issue. A function I created appears to be almost corrupting any loop it is placed in. However, outside of loops, it works perfectly fine.

The function in question is:

function findQuoted(s)
{
    var Quote = 0;
    var F = 0;
    var L = 0;
    var Strings = Array();
    for(i = 0;i < s.length;i++)
    {
        if(s.charAt(i) == '"' && Quote == 0)
        {
            Quote = 1;
            F = i;
        }
        else if(s.charAt(i) == '"' && Quote == 1)
        {
            Strings[Strings.length] = s.substring(F, i + 1);
            Quote = 0;
        }
    }
    return Strings;
}

http://pastebin.com/2wi4Tnn8

If this is executed in any loop, for some odd reason, the loop just ceases to work, and runs only once.

In this example, the alert messages are displayed only once each before continuing the program. Keep in mind, the program never gets stuck or goes non-responsive, the loop just ceases to function.

for(i = 0;i < 5;i++)
{
    alert(findQuoted('"Test" this is a test "test" another test "TEST"'));
    alert('test');
}

In a normal scenario, without this function being used, everything in this loop is executed 6 times. Due to this function being present in the loop, however, everything in this function is only executed one time.

000
  • 26,951
  • 10
  • 71
  • 101
NAME__
  • 625
  • 1
  • 7
  • 17
  • 1
    jsLint on your code would have pointed out the undeclared reference to `i` in your `for` loop. Valuable tool worth using. – jfriend00 Jul 12 '13 at 19:41

1 Answers1

9

Use

for(var i = 0;i < 5;i++)

otherwise you're using the same variable i that you're using to iterate over in your other loop.

Ian
  • 50,146
  • 13
  • 101
  • 111
Dek Dekku
  • 1,441
  • 11
  • 28
  • Well spotted! This question also sheds more light on why this is needed: http://stackoverflow.com/questions/2485423/javascript-is-using-var-to-declare-variables-optional – Richard Jul 12 '13 at 19:33
  • This worked, thanks. I wasn't even aware that JavaScript allowed you to declare variables being used in for loops. I'll keep this in mind in the future. – NAME__ Jul 12 '13 at 19:35
  • 2
    @user2577669 Note that the variable is not declared in the scope of that loop, but rather the function that the loop is within. Javascript has function scope. If you don't use the `var` keyword though, you are using the global context. – Paul Jul 12 '13 at 19:37