现象
-
下面这个代码的输出毫无疑问,是true;
const reg = /\d+/g; //匹配数字 reg.test(11111); // true
-
如果我接着再test一遍呢
const reg = /\d+/g; //匹配数字 reg.test(11111); // true reg.test(11111); // false
这就是血案本案了
-
lastIndex观察
const reg = /\d+/g; //匹配数字 console.log(reg.test(11111), reg.lastIndex); // true, 0 console.log(reg.test(11111), reg.lastIndex); // false, 5 console.log(reg.test(11111), reg.lastIndex); // true, 0 console.log(reg.test(11111), reg.lastIndex); // false, 5 console.log(reg.test(11111), reg.lastIndex); // true, 0 console.log(reg.test(11111), reg.lastIndex); // false, 5
-
MDN中对于exec和test有如下介绍
在设置了 global 或 sticky 标志位的情况下(如 /foo/g or /foo/y),JavaScript RegExp 对象是有状态的。他们会将上次成功匹配后的位置记录在 lastIndex 属性中
-
处理方案1
避免在test时使用g(废话); -
处理方案2
每次test创建新的正则对象 :/\d/g.test(11111) // true /\d/g.test(11111) // true /\d/g.test(11111) // true /\d/g.test(11111) // true
这其实也不太好,每次都实例化出一个新的正则对象;
-
处理方案3
lastIndex是可写的!!
那就可以这样了:const reg = /\d+/g; //匹配数字 reg.test(11111); // true reg.lastIndex = 0; reg.test(11111); // true
目前想到的就这三种,后面有想到其它的再来补吧;