为什么RegExp.prototype.exec()的返回值会变化

来源:互联网 发布:超级优化基因液txt免费 编辑:程序博客网 时间:2024/05/20 00:36

1 环境

node:v6.11.1

2 问题

为了方便,我在node环境下测试RegExp.exec()
测试结果如下:

这里写图片描述

我们可以看到:同样的代码,返回的结果是交替变化的这是为什么呢?

3 原因

还是要看文档:

Finding successive matches
If your regular expression uses the “g” flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression’s lastIndex property .

文档里说正则表达式有一个lastIndex属性,每次搜索都会从这个属性指明的位置开始。而这个属性每次匹配成功后都会更新到匹配结束的位置。

我们从下图红框中的内容可以看到:lastIndex是被更新了。
这就是为什么exec返回的结果交替变化的原因:每次搜索的范围变了。

这里写图片描述

原创粉丝点击