Javascript lastIndex 正則表達式的一個疑惑
更新時間:2009年01月13日 00:54:46 作者:
Javascript lastIndex 正則表達式
看下面這段代碼:
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行并沒有產(chǎn)生新的正則表達式,其之前的屬性lastIndex還保留著(lastIndex=1)。這有點不合常理,頭疼中。。。。。。
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行并沒有產(chǎn)生新的正則表達式,其之前的屬性lastIndex還保留著(lastIndex=1)。這有點不合常理,頭疼中。。。。。。

