是更好地使用RegExp对象或内联样式?为什么?
Is it better to use the RegExp object or the inline style? And why?
推荐答案据该ES3的规范,他们是在稍有不同的文字语法( /正则表达式/ )在初始扫描将创建一个正则表达式对象:
According to the ES3 specification, they are slightly different in that the literal syntax (/regex/) will create a single RegExp object upon the initial scan:
一个普通的前pression literal是 被转换为输入元件 RegExp对象(第15.10),当它 被扫描。在创建对象 包含的评价之前, 程序或函数开始。评估 的字面产生一个参考 该对象;它不会创建一个新的 对象。
A regular expression literal is an input element that is converted to a RegExp object (section 15.10) when it is scanned. 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.
在规范的错误是在ES4承认:
The error in that spec was acknowledged in ES4:
在ES3一个普通的前pression字面 像/ AB /毫克表示一个唯一的 所创建的RegExp对象 第一次遇到的字面 评估期间。在ES4新 RegExp对象被创建的的每次的 字面的过程中遇到 评价。
In ES3 a regular expression literal like /ab/mg denotes a single unique RegExp object that is created the first time the literal is encountered during evaluation. In ES4 a new RegExp object is created every time the literal is encountered during evaluation.
实现跨浏览器的不同而不同。 Safari和IE浏览器把文字按ES4,但Firefox和Chrome似乎视他们为每ES3。
Implementations vary across browsers. Safari and IE treat literals as per ES4, but Firefox and Chrome appear to treat them as per ES3.
尝试在不同的浏览器下code,你就会明白我的意思:
Try the following code in various browsers and you'll see what I mean:
function f() { return /abc/g.test('abc'); } alert(f()); // Alerts true alert(f()); // Alerts false in FF/Chrome则为:
function f() { return RegExp('abc', 'g').test('abc'); } alert(f()); // Alerts true alert(f()); // Alerts true请注意,假的,是因为该功能仍然使用从功能, lastIndex的其中被更新的previous调用正则表达式,这意味着惊动它不会匹配字符串ABC了。
Note, false is alerted because the function is still using the regex from the previous call of that function, the lastIndex of which was updated, meaning that it won't match the string "abc" anymore.
提示:不需要正则表达式来实例化新的运营商。 的RegExp()本身的工作原理相同...
Tip: the new operator is not required for RegExp to be instantiated. RegExp() by itself works the same...
在ES3 / 4的问题更多信息:stackoverflow/questions/1534098/regex-lastindex-unexpected-behaviour
More info on the ES3/4 issue: stackoverflow/questions/1534098/regex-lastindex-unexpected-behaviour
更多推荐
是内联JavaScript正前pressions更快?
发布评论