是内联JavaScript正前pressions更快?

编程入门 行业动态 更新时间:2024-10-18 01:33:35
本文介绍了是内联JavaScript正前pressions更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是更好地使用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更快?

本文发布于:2023-06-05 23:05:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/531118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内联   更快   JavaScript   pressions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!