// 声明一个正则对象const reg = /^1[345678][0-9]{9}$/g;// 下面2个打印结果不同 ? console.log(reg.lastIndex, reg.test(15328044636)); // 0 trueconsole.log(reg.lastIndex, reg.test(15328044636)); // 11 false/* 产生这个问题原因* 这是因为正则reg的g属性,设置的全局匹配。RegExp有一个lastIndex属性,来保存索引开始位置。上面的问题,第一次调用的lastIndex值为0,到了第二次调用,值变成了11。*解决方案第一种方案是将g去掉,关闭全局匹配。第二种就是在每次匹配之前将lastIndex的值设置为0。/const reg = /^1[345678][0-9]{9}$/gi;console.log(reg.lastIndex, reg.test(15328044636));reg.lastIndex = 0;console.log(reg.lastIndex, reg.test(15328044636));//打印的值0 true0 true