问题
var matches;
while(matches = /./g.exec("abc"))
{
console.log("hey");
}
This never terminates. I expect it to terminate after 3 loops.
Warning: Don't run it in Chrome because the infinite log lines freeze your entire system. It's safe to run it in IE (it still freezes your webpage but you can go to the location bar and press enter to reload).
回答1:
This is how you should execute exec
in a loop:
var matches;
var re = /./g;
while(matches = re.exec("abc")) {
if (matches.index === re.lastIndex)
re.lastIndex++;
console.log("hey");
}
Keep regex in a separate variable rather than using regex literal.
Also if
lastIndex
(matched position) of regex is same asindex
property of resulting array then incrementlastIndex
by 1.
回答2:
It's because you are creating a new object with the g
flag every time, instead of keeping one regex object. The regex object keeps track of the last match. Since you are creating new objects every time, the object starts from the beginning.
Each regex literal is it's own object that's why:
/./g !== /./g
来源:https://stackoverflow.com/questions/33015942/regex-exec-loop-never-terminates-in-js