简体   繁体   English

为什么.test() 和.match() 有相反的语法? 这背后的原因是什么?

[英]Why .test() and .match() have opposite syntax? What's the reason behind that?

I just learned about those methods and tried to google it, but found nothing我刚刚了解了这些方法并试图用谷歌搜索,但一无所获

'string'.match(/regex/);
/regex/.test('string');

Why do they take /regex/ and 'string' vice versa?为什么他们采用/regex/'string'反之亦然?

(Reposting my comment as an answer) (重新发布我的评论作为答案)

Because a String isn't a RegExp and vice-versa.因为String不是正则RegExp ,反之亦然。

If the JavaScript standard library did use the same function name in both cases then it would cause confusion because the two methods return very different values.如果 JavaScript 标准库在这两种情况下确实使用了相同的 function 名称,那么这会导致混淆,因为这两种方法返回的值非常不同

JavaScript does not implement static-typing so without using the different names match and test someone reading the code wouldn't know if the return value type is string[] | null JavaScript 没有实现静态类型,因此如果不使用不同的名称matchtest阅读代码的人将不知道返回值类型是否为string[] | null string[] | null or bool (remember also that JavaScript doesn't allow true function overloading). string[] | nullbool (还要记住 JavaScript 不允许真正的 function 过载)。

See regex.test VS string.match to know if a string matches a regular expression请参阅regex.test VS string.match 以了解字符串是否与正则表达式匹配

  • String.match returns string[] | null String.match返回string[] | null string[] | null . string[] | null
  • RegExp.test returns bool . RegExp.test返回bool

So if you see this code...:因此,如果您看到此代码...:

function doSomething( foo, bar ) {

    return foo.match( bar );
}

...then (assuming foo is a string ) then you know that doSomething will return a string[] | null ...然后(假设foo是一个string )那么你知道doSomething将返回一个string[] | null string[] | null value. string[] | null值。

And if you see this...:如果你看到这个......:

function doSomething( foo, bar ) {

    return foo.test( bar );
}

...Then (assuming foo is a RegExp ) then you know that doSomething will return a bool value. ...然后(假设fooRegExp )然后你知道doSomething将返回一个bool值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM