比如我测试一个字符窜
let reg = /\d/g;
let str = "a1b2c3d4";
let str2 = "e6f7g8";
console.log(reg.test(str),reg.lastIndex);
console.log(reg.test(str),reg.lastIndex);
console.log(reg.test(str),reg.lastIndex);
console.log(reg.test(str),reg.lastIndex);
console.log(reg.test(str2),reg.lastIndex); //期望输出的是true,结果是false
console.log(reg.test(str),reg.lastIndex);
输出是:
true 2
true 4
true 6
true 8
false 0
true 2
当我传入新的str字符串,reg应该再重头开始匹配,换句话说,lastIndex应该是和str,reg都关联才对。那为什么要在reg中保存这个变量呢?有什么意义呢?如何解决上述情况的问题。
lastindex是可读写的,也就是可以让你手动配置开始匹配的位置。在某种使用场景下可以加快匹配的速度