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