为什么我的Javascript中的两个正则表达式文字在属性上有所不同? [英] Why do two regex literals in my Javascript vary on a property?

查看:99
本文介绍了为什么我的Javascript中的两个正则表达式文字在属性上有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Douglas Crockford的 Javascript:The Good Parts 中读到javascript正则表达式文字共享同一个对象。如果是这样,那么这两个正则表达式文字如何在 lastIndex 属性中变化?

I read in Javascript: The Good Parts by Douglas Crockford that javascript regular expression literals share the same object. If so, then how come these two regex literals vary in the lastIndex property?

var a = /a/g;
var b = /a/g;

a.lastIndex = 3;
document.write(b.lastIndex);​

JS小提琴

输出0而不是3。

推荐答案

ECMAScript文档非常清楚它们是两个不同的对象:

Section 7.8.5 of the ECMAScript Documentation makes it quite clear they are two different objects:


7.8.5正则表达式文字

正则表达式文字是一个输入元素,每次计算文字时都会转换为RegExp对象(见15.10)。程序中的两个正则表达式文字计算为正则表达式对象,即使两个文字的内容相同,它们也绝不会相互比较为===。 RegExp对象也可以在运行时由新的RegExp创建(参见15.10.4)或将RegExp构造函数作为函数调用(15.10.3)。

7.8.5 Regular Expression Literals
A regular expression literal is an input element that is converted to a RegExp object (see 15.10) each time the literal is evaluated. Two regular expression literals in a program evaluate to regular expression objects that never compare as === to each other even if the two literals' contents are identical. A RegExp object may also be created at runtime by new RegExp (see 15.10.4) or calling the RegExp constructor as a function (15.10.3).

这篇关于为什么我的Javascript中的两个正则表达式文字在属性上有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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