Jump to content

For Loop Condition?


tinfanide

Recommended Posts

window.onload = function(){var str = "This is is is.";var patt = /Th/gi;for( var count = 0; patt.exec(str); ++count );    alert(count);}

I've got two parts I can't tell why and how.First,

patt.exec(str)

Why can it be inserted as a condition? What does it mean? I can tell from the effect that it serves as counting the pattern in the string. But just can't understand how. Second,Why is ++count, not count++?I know people explain like ++count increments the variable before the argument while the other the other way round.But I still don't get it in this case.What is the difference if I set it as count++? (I know it cannot run the for loop) But just why is that???

Link to comment
Share on other sites

The condition that stops the loop can be anything that evaluates to true or false. The loop stops when the condition evaluates to false. The exec method returns null if there are no matches, so the loop will basically count how many matches it found. In this case, there's no difference in using the pre-increment versus post-increment, since the count variable is not checked in the condition to end the loop. Notice that the alert statement is not part of the loop. You have it indented like it is, but it's not. There is a semicolon after the for statement, so the loop is empty (it only increments the counter). That loop is the same as these:

for( var count = 0; patt.exec(str); ++count ){ }alert(count); for( var count = 0; patt.exec(str); count ){  count++;}alert(count);

It runs the loop first, then alerts the count.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...