var matches;
while(matches = /./g.exec("abc"))
{
console.log("hey");
}
这永远不会终止。我希望它在 3 个循环后终止。
警告:不要在 Chrome 中运行它,因为无限的日志行会卡住您的整个系统。在 IE 中运行它是安全的(它仍然会卡住您的网页,但您可以转到地址栏并按回车键重新加载)。
最佳答案
这是在循环中执行 exec
的方式:
var matches;
var re = /./g;
while(matches = re.exec("abc")) {
if (matches.index === re.lastIndex)
re.lastIndex++;
console.log("hey");
}
将正则表达式保存在单独的变量中,而不是使用正则表达式文字。
此外,如果正则表达式的
lastIndex
(匹配位置)与结果数组的index
属性相同,则将lastIndex
递增 1。
关于javascript - 正则表达式 exec() 循环永远不会在 JS 中终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33015942/