开发者

Why does this JavaScript code with a regex not work as I expected?

开发者 https://www.devze.com 2023-03-27 02:48 出处:网络
a = /\\d+/.exec; 开发者_JS百科 a(\"hello,123\") I getting the following error: Error: can\'t convert undefined to object
a = /\d+/.exec; 开发者_JS百科
a("hello,123")

I getting the following error:

Error: can't convert undefined to object

Why is a returned as undefined?


a in this case is a reference to the RegExp.prototype.exec function itself, and is not actually bound to any regular expression. Either of these would work:

var a = /\d+/.exec('hello,123');

var rx = /\d+/,
     a = rx.exec;

a.call(rx, 'hello,123');

Your undefined is coming from an internal reference to this from within the exec function.

0

精彩评论

暂无评论...
验证码 换一张
取 消