为什么“g”指的是“g”。当test()被调用两次时,修饰符给出不同的结果? [英] Why does the "g" modifier give different results when test() is called twice?

查看:128
本文介绍了为什么“g”指的是“g”。当test()被调用两次时,修饰符给出不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

var reg = /a/g;
console.log(reg.test("a"));
console.log(reg.test("a"));

我得到这个结果:

true
false

我不知道这怎么可能发生。我已在Node.js(v8)和Firefox浏览器中进行过测试。

I have no idea how this could happen. I have tested in both Node.js (v8) and Firefox browser.

推荐答案

要解决此问题,可以删除 g 标记或重置 lastIndex ,如

To workaround the problem, you can remove the g flag or reset lastIndex as in

var reg = /a/g;
console.log(reg.test("a"));
reg.lastIndex = 0;
console.log(reg.test("a"));

问题出现是因为 test 基于 exec 在第一个之后查找更多匹配项,如果传递相同的字符串并且存在 g 标志。

The problem arises because test is based around exec which looks for more matches after the first if passed the same string and the g flag is present.


15.10.6.3 RegExp.prototype.test(字符串)#ⓉⓇ

采取以下步骤:


  1. 匹配成为评估 RegExp的结果.prototype.exec (15.10.6.2)算法在此 RegExp 对象上使用 string 作为参数。

  2. 如果匹配不是 null ,则返回 true ;否则返回 false

  1. Let match be the result of evaluating the RegExp.prototype.exec (15.10.6.2) algorithm upon this RegExp object using string as the argument.
  2. If match is not null, then return true; else return false.


密钥 exec 的一部分是 15.10的第6步。 6.2


6。设global是调用带有参数global的R的[[Get]]内部方法的结果。

7.如果global为false,则让i = 0.。

6. Let global be the result of calling the [[Get]] internal method of R with argument "global".
7. If global is false, then let i = 0.

i 未重置为0时,则 exec (因此 test )不会开始查看字符串的开头。

When i is not reset to 0, then exec (and therefore test) does not start looking at the beginning of the string.

这对于 exec 因为您可以循环处理每个匹配:

This is useful for exec because you can loop to handle each match:

 var myRegex = /o/g;
 var myString = "fooo";
 for (var match; match = myRegex.exec(myString);) {
   alert(match + " at " + myRegex.lastIndex);
 }

但显然它对测试没那么有用

这篇关于为什么“g”指的是“g”。当test()被调用两次时,修饰符给出不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆