javascript字符串exec奇怪的行为 [英] javascript string exec strange behavior

查看:144
本文介绍了javascript字符串exec奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的对象中有定期调用的函数。

have funciton in my object which is called regularly.

parse : function(html)
{
    var regexp = /...some pattern.../
    var match = regexp.exec(html);
    while (match != null)
    {
        ...
        match = regexp.exec(html);
    }
    ...
    var r = /...pattern.../g;
    var m = r.exec(html);
}

未更改html m 每次调用都返回null。让我们说

with unchanged html the m returns null each other call. let's say

parse(html);// ok
parse(html);// m is null!!!
parse(html);// ok
parse(html);// m is null!!!
// ...and so on...

是否有任何索引或somrthing必须在 html上重置 ...我真的很困惑。为什么匹配总是返回正确的结果?

is there any index or somrthing that has to be reset on html ... I'm really confused. Why match always returns proper result?

推荐答案

这是一种常见的行为处理具有全局 g 标志的模式时,使用 exec 测试方法。

This is a common behavior when you deal with patterns that have the global g flag, and you use the exec or test methods.

在这种情况下, RegExp 对象将跟踪< a href =https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex\"rel =nofollow noreferrer> lastIndex 找到匹配的地方,然后在后续匹配中,它将从 lastIndex 开始,而不是从0开始。

In this case the RegExp object will keep track of the lastIndex where a match was found, and then on subsequent matches it will start from that lastIndex instead of starting from 0.

编辑:为了回应您的评论,为什么在您再次调用该函数时不会重新创建 RegExp 对象

In response to your comment, why doesn't the RegExp object being re-created when you call the function again:

这是正则表达式文字所描述的行为,让我引用规范:

This is the behavior described for regular expression literals, let me quote the specification:

§ 7.8.5 - 正则表达式文字


...

...

在评估包含的程序或函数开始之前创建对象。对文字的评价产生对该对象的引用;它不会创建新对象。

The object is created before evaluation of the containing program or function begins. Evaluation of the literal produces a reference to that object; it does not create a new object.

....

您可以通过以下方式进行简单的证明:

You can make a simple proof by:

function createRe() {
  var re = /foo/g;
  return re;
}

createRe() === createRe(); // true, it's the same object

你可以确定它是同一个对象,因为程序中的两个正则表达式文字计算为正则表达式对象,即使两个文字的内容相同,也不会相互比较为 === ,例如:

You can be sure that is the same object, because "two regular expression literals in a program evaluate to regular expression objects that never compare as === to each other even if the two literals' contents are identical", e.g.:

/foo/ === /foo/; // always false...

但是这种行为在所有浏览器上都受到尊重,但不受IE的影响每次都初始化一个新的RegExp对象。

However this behavior is respected on all browser but not by IE, which initializes a new RegExp object every time.

这篇关于javascript字符串exec奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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