[英]Regex/lastIndex - Unexpected behaviour
I know there are a few regex/ lastIndex
discrepancies but this one is new to me! 我知道regex / lastIndex
有一些差异,但这对我来说是新的!
Expected behaviour : Creating a new regular expression (with literal/constructor) will, obviously, create a new RegExp object with a lastIndex
property set to zero. 预期的行为 :创建新的正则表达式(带有文字/构造函数)显然会创建一个新的RegExp对象,其lastIndex
属性设置为零。
Actual behaviour : (in FF, Chrome): The lastIndex property seems to persist through multiple RegExp creations. 实际行为 :(在FF,Chrome中):lastIndex属性似乎在多个RegExp创建过程中仍然存在。
Eg 例如
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');
See here: http://jsbin.com/otoze 看到这里: http : //jsbin.com/otoze
A new RegExp object is being created on every function call (right?), so why is the following being written to the document?? 在每个函数调用上都会创建一个新的RegExp对象(对吗?),为什么将以下内容写入文档? - --
0
3
6
??? ???
Note, this weirdness appears to happen in FF(3) and Chrome(2), but, curiously not IE. 请注意,这种怪异现象似乎发生在FF(3)和Chrome(2)中,但奇怪的是没有IE。
Is this expected behaviour, does IE get it wrong or right? 这是预期的行为吗,IE会错还是对? Is this a well-known bug? 这是一个众所周知的错误吗?
EDIT: this doesn't appear to happen when instantiating the regex with a constructor instead of a literal. 编辑:使用构造函数而不是文字实例化正则表达式时,似乎不会发生这种情况。 Eg new RegExp('ABC','g');
例如new RegExp('ABC','g');
... Still, the literal should (theoretically) work, right? ...仍然,字面意义(理论上)应该起作用,对吗?
var regex = new RegExp("ABC", "g");
doesn't have that problem, so I guess /ABC/g
re-uses regexp objects. 没有这个问题,所以我猜/ABC/g
重新使用了regexp对象。
EDIT: Apparently this is correct behavior according to the ECMAScript 3.0 specification, it's fixed in ECMAScript 3.1 - details 编辑:显然,这是根据ECMAScript 3.0规范的正确行为,已在ECMAScript 3.1中修复- 详细信息
Try this: 尝试这个:
function foo(s) {
// A *NEW* regular expression
// is created on each call of foo():
var regex = new 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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.