看下面這段代碼:
- function test(s){
- var reg = /./g;
- console.log(reg.exec(s));
- console.log(reg.lastIndex);
- var reg = /./g;
- console.log(reg.exec(s));
- console.log(reg.lastIndex);
- }
- test("abcd");
- test("efgh");
我以為輸出的lastIndex的值應該都是1,但是實際上的輸出如下:
a
1
a
1
f
2
f
2
感覺就像是在第二次調用test的時候第2行和第6行并沒有產生新的正則表達式,其之前的屬性lastIndex還保留著(lastIndex=1)。這有點不合常理,頭疼中。。。。。。