带有/g的Javascript Regex文字多次使用 [英] Javascript Regex literal with /g used multiple times
问题描述
我在使用Javascript Regexp.exec函数时遇到了一个奇怪的问题.在新的(我想是...)regexp对象上多次调用该函数时,它每两个就会工作一次.我根本不明白为什么!
I have a weird issue working with the Javascript Regexp.exec function. When calling multiple time the function on new (I guess ...) regexp objects, it works one time every two. I don't get why at all!
这是一个小循环示例,但在函数中使用一次并多次调用时,它会执行相同的操作.
Here is a little loop example but it does the same thing when used one time in a function and called multiple times.
for (var i = 0; i < 5; ++i) {
console.log(i, (/(b)/g).exec('abc'));
}
> 0 ["b", "b"]
> 1 null
> 2 ["b", "b"]
> 3 null
> 4 ["b", "b"]
删除/g时,它恢复正常.
When removing the /g, it gets back to normal.
for (var i = 0; i < 5; ++i) {
console.log(i, (/(b)/).exec('abc'));
} /* no g ^ */
> 0 ["b", "b"]
> 1 ["b", "b"]
> 2 ["b", "b"]
> 3 ["b", "b"]
> 4 ["b", "b"]
我猜有一个优化,保存了regexp对象,但这似乎很奇怪.
I guess that there is an optimization, saving the regexp object, but it seems strange.
此行为在Chrome 4和Firefox 3.6上相同,但其工作方式与IE8中的(I)相同.我相信这是有意的,但我找不到那里的逻辑,也许您将能够为我提供帮助!
This behaviour is the same on Chrome 4 and Firefox 3.6, however it works as (I) expected in IE8. I believe that is intended but I can't find the logic in there, maybe you will be able to help me!
谢谢