看下面这段代码:我以为输出的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");
a
1
a
1
f
2
f
2
感觉就像是在第二次调用test的时候第2行和第6行并没有产生新的正则表达式,其之前的属性lastIndex还保留着(lastIndex=1)。这有点不合常理,头疼中。。。。。。
本文通过一段示例代码探讨了 JavaScript 中正则表达式的 lastIndex 属性的行为,特别是当同一正则表达式被重复使用时 lastIndex 的表现,并提出了对于预期行为与实际表现差异的疑惑。
220

被折叠的 条评论
为什么被折叠?



