为什么我的javascript regex.test()给出了交替的结果 [英] why does my javascript regex.test() give alternating results
问题描述
var r = /\d/g;
var a = r.test("1"); // will be true
var b = r.test("1"); // will be false
console.log(a == b); // will be false
请向我解释为什么 r的结果。测试(1)
交替进行每次通话?
Please explain to me why the result of r.test("1")
alternates with each call?
通过删除g修饰符,我能够解决我遇到的问题。但是我仍然想知道为什么会发生这种情况。
I was able to work around the issue I was having by removing the g modifier. However I would still like to understand why this happens.
推荐答案
当你使用 / g
,正则表达式对象将在调用之间保存状态(因为您应该使用它来匹配多个调用)。它匹配一次,但后续调用从原始匹配开始。
When you're using /g
, the regex object will save state between calls (since you should be using it to match over multiple calls). It matches once, but subsequent calls start from after the original match.
(这是 Javascript正则表达式返回true ..然后为false ..然后为真......等等)
(This is a duplicate of Javascript regex returning true.. then false.. then true.. etc)
这篇关于为什么我的javascript regex.test()给出了交替的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!