Regex / lastIndex - 意外行为 [英] Regex/lastIndex - Unexpected behaviour

查看:85
本文介绍了Regex / lastIndex - 意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一些正则表达式/ lastIndex 差异,但这个对我来说是新的!

I know there are a few regex/lastIndex discrepancies but this one is new to me!

预期行为:显然,创建一个新的正则表达式(带有文字/构造函数)将创建一个带有 lastIndex的新RegExp对象 属性设置为零。

Expected behaviour: Creating a new regular expression (with literal/constructor) will, obviously, create a new RegExp object with a lastIndex property set to zero.

实际行为 :(在FF,Chrome中):lastIndex属性似乎坚持多个RegExp创作。

Actual behaviour: (in FF, Chrome): The lastIndex property seems to persist through multiple RegExp creations.

例如

function foo(s) {

    // A *NEW* regular expression
    // is created on each call of foo():
    var regex = /ABC/g;

    document.write( regex.lastIndex + '<br/>' );

    // regex.test() updates lastIndex property
    regex.test(s);

    // This is where the regex's life should end...
    // (Why does it persist?)

}

foo('ABC');
foo('ABCABC');
foo('ABCABCABC');

见这里: http://jsbin.com/otoze

See here: http://jsbin.com/otoze

正在为每个函数调用创建一个新的RegExp对象(对吗?),为什么以下内容被写入文档? -

A new RegExp object is being created on every function call (right?), so why is the following being written to the document?? -

0
3
6

???

注意,这种奇怪现象似乎发生在FF(3)和Chrome(2)中但是,奇怪的是不是IE。

Note, this weirdness appears to happen in FF(3) and Chrome(2), but, curiously not IE.

这是预期的行为,IE是错误的还是对的?这是一个众所周知的错误吗?

Is this expected behaviour, does IE get it wrong or right? Is this a well-known bug?

编辑:当使用构造函数实例化正则表达式时,这似乎不会发生而不是文字。例如。 新的RegExp('ABC','g'); ......但是,文字应该(理论上)正常工作,对吗?

this doesn't appear to happen when instantiating the regex with a constructor instead of a literal. E.g. new RegExp('ABC','g'); ... Still, the literal should (theoretically) work, right?

推荐答案

var regex = new RegExp(ABC,g); 没有那个问题,所以我猜 / ABC / g 重新使用正则表达式对象。

var regex = new RegExp("ABC", "g"); doesn't have that problem, so I guess /ABC/g re-uses regexp objects.

编辑:显然这是根据ECMAScript 3.0规范的正确行为,它已在ECMAScript 3.1中修复 - 详情

Apparently this is correct behavior according to the ECMAScript 3.0 specification, it's fixed in ECMAScript 3.1 - details

这篇关于Regex / lastIndex - 意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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