困扰了很长一段时间的Javascript的一个BUG

原文:http://blog.csdn.net/yycai/archive/2009/01/12/3760366.aspx

 

 

问了好多人,都没有得到一个满意的答复,终于忍不住在TopLanguage提问了一下,呵呵,终于有高人回复了,原来是一个bug:

http://code.google.com/p/chromium/issues/detail?id=2161

https://bugzilla.mozilla.org/show_bug.cgi?id=98409#c35

 

摘录如下:

Looking at the reduced test case, there is a regular expression literal on line 5.  
According to the spec, there is only one instance of a regular expression literal
(ECMA 262 7.8.5), which is created when the literal is scanned. So each time jsfGetFormDate is called, a new RegExp object is not created. Instead the same
RegExp object is reused over and over again.

Since the 'g' flag is specified, that means that the global property is true for the
RegExp object (ECMA 262 15.10.4.1). In the case where the global property is true,
when exec successfully finds a match, the lastIndex property of the RegExp is set to one plus the index of the last input character matched so far (ECMA 262 15.10.2.1,
15.10.6.2 step 11). So in this case lastIndex is 10 after the first call to jsfGetFormDate, since the length of the input string is 10 and the complete string is
matched.

Remember that there is only one instance of the regular expression literal RegExp
object, so the next time jsfGetFormDate is called, the lastIndex property of the
RegExp object is still 10. So the next time exec is called, it attempts to match
starting at index 10 of the input string (ECMA 262 15.10.6.2 step 7). Since the
input string is only 10 characters in length, no match is found. Then it tries again
starting at index 11 (ECMA 262 15.10.6.2 steps 8 and 9) and, because 11 is greater
than the length of the input string (which is 10), it fails and returns null (ECMA
262 15.10.6.2 step 6).

----------------------------------------

Potential workarounds:

1. Do not specify the global 'g' flag in the regular expression.

2. Instead of using a regular expression literal, instead use something like this:

var p = '(0?//d{1,2})[///-]0?//d{1,2}[///-]//d{4}';
var re = new RegExp(p, 'g');

which will create a new RegExp object each time.



当然你也可以在每次使用之前把它的lastIndex属性设为0~~


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值