Symbol.match
Symbol.match
静态数据属性代表 众所周知的符号 Symbol.match
。String.prototype.match()
方法在其第一个参数上查找此符号,以查找用于将输入字符串与当前对象进行匹配的方法。该符号还用于确定对象是否应为 被视为正则表达式。
¥The Symbol.match
static data property represents the well-known symbol Symbol.match
. The String.prototype.match()
method looks up this symbol on its first argument for the method used to match an input string against the current object. This symbol is also used to determine if an object should be treated as a regex.
有关详细信息,请参阅 RegExp.prototype[Symbol.match]()
和 String.prototype.match()
。
¥For more information, see RegExp.prototype[Symbol.match]()
and String.prototype.match()
.
Try it
值
描述
¥Description
该函数也用于识别 如果对象具有正则表达式的行为。例如,方法 String.prototype.startsWith()
、String.prototype.endsWith()
和 String.prototype.includes()
,检查它们的第一个参数是否是正则表达式,如果是,则抛出 TypeError
。现在,如果 match
符号设置为 false
(或除 undefined
之外的 假值 值),则表明该对象不打算用作正则表达式对象。
¥This function is also used to identify if objects have the behavior of regular expressions. For example, the methods String.prototype.startsWith()
, String.prototype.endsWith()
and String.prototype.includes()
, check if their first argument is a regular expression and will throw a TypeError
if they are. Now, if the match
symbol is set to false
(or a Falsy value except undefined
), it indicates that the object is not intended to be used as a regular expression object.
示例
将 RegExp 标记为非正则表达式
¥Marking a RegExp as not a regex
以下代码将抛出 TypeError
:
¥The following code will throw a TypeError
:
"/bar/".startsWith(/bar/);
// Throws TypeError, as /bar/ is a regular expression
// and Symbol.match is not modified.
但是,如果将 Symbol.match
设置为 false
,则该对象将被视为 不是正则表达式对象。因此,方法 startsWith
和 endsWith
不会抛出 TypeError
。
¥However, if you set Symbol.match
to false
, the object will be considered as not a regular expression object. The methods startsWith
and endsWith
won't throw a TypeError
as a consequence.
const re = /foo/;
re[Symbol.match] = false;
"/foo/".startsWith(re); // true
"/baz/".endsWith(re); // false
规范
Specification |
---|
ECMAScript Language Specification # sec-symbol.match |
浏览器兼容性
BCD tables only load in the browser