关于reg.lastIndex

vue的data中:

reg:/1\d{10}/g,
 
然后定义了一个过滤器:
filters:{
        testStr(value,reg){   
            console.log(reg.test(value));//true
            console.log(reg.test(value));//false
            return reg.test(value);
        },
    }

  

两次输入居然不一样,原来正则regg属性,设置的全局匹配。RegExp有一个lastIndex属性,来保存索引开始位置;第一次lastIndex为0,第二次lastIndex为11

filters:{
        testStr(value,reg){   
            console.log(reg.test(value));//true
            reg.lastIndex = 0;
            console.log(reg.test(value));//true
            return reg.test(value);
        },
    }

猜你喜欢

转载自www.cnblogs.com/longsiyuan/p/11990581.html