???这个结果是bug还是其他原因,不应该全部为true吗,
发布于 4 年前 作者 chenkai0520 4484 次浏览 来自 问答

怀疑人生了 屏幕快照 2019-12-27 18.28.53.png

方便测试代码贴出来了

let reg = /[A-Z]+/g
let data = ['A','B','C','D','E'];

data.forEach((element,index)=>{
    console.log(`${reg}.test('${element}')`,reg.test(element))
});

// /[A-Z]+/g.test('A') true
// /[A-Z]+/g.test('B') false
// /[A-Z]+/g.test('C') true
// /[A-Z]+/g.test('D') false
// /[A-Z]+/g.test('E') true
4 回复

找到问题了/g的原因 如果正则表达式设置了全局标志,test() 的执行会改变正则表达式 lastIndex属性。连续的执行test()方法,后续的执行将会从 lastIndex 处开始匹配字符串,(exec() 同样改变正则本身的 lastIndex属性值).

下面的实例表现了这种行为:

var regex = /foo/g;

// regex.lastIndex is at 0 regex.test(‘foo’); // true

// regex.lastIndex is now at 3 regex.test(‘foo’); // false

使用 regexp.test() 方法一定得知道 /g 模式的坑。 所以我基本禁用 test()

我之前也遇到过这个问题

回到顶部