RegExp 等价于 array.indexOf( str )

发布于 2024-12-18 10:56:13 字数 219 浏览 2 评论 0原文

给定一个包含字符串值的变量 str,这两行代码是否等价?

A线:

if ( [ 'foo', 'bar', 'baz' ].indexOf( str ) > -1 ) {

B线:

if ( /^foo|bar|baz$/.test( str ) ) {

Given a variable str containing a string value, are these two lines of code equivalent?

Line A:

if ( [ 'foo', 'bar', 'baz' ].indexOf( str ) > -1 ) {

Line B:

if ( /^foo|bar|baz$/.test( str ) ) {

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘦怹 2024-12-25 10:56:13

不完全是。管道包括 ^$ 作为替代。我不太清楚 JS 正则表达式的语法,但是如果您正在寻找仅包含 foobarstrbaz,使用表达式 /^(foo|bar|baz)$/。如果您想做一些不同的事情,请告诉我,我会尽力解决它。

Not quite. The pipes are including the ^ and $ as alternatives. I'm not entirely clear on the syntax of JS's regular expressions, but if you're looking for str to contain only foo, or bar, or baz, use the expression /^(foo|bar|baz)$/. If you're looking to do something different, let me know and I'll try to clear it up.

奶茶白久 2024-12-25 10:56:13

不,他们不是。

方法 indexOf() 返回如果在数组中未找到该项目,则为 -1;如果在数组中找到该项目,则为该数组的位置。

方法 test 返回true;如果没有,则为 false

如果您的正则表达式是 /^(foo|bar|baz)$/,那么函数将是相同的。

No, they are not.

The method indexOf() returns -1 if the item is not found in the array, or the position of the array if it is found in the array.

The method test returns true if the regex finds a match, and false if it doesn't.

If your regular expression was instead /^(foo|bar|baz)$/, then the function would be the same.

青朷 2024-12-25 10:56:13

好的,编辑后,它们仍然不等效,因为 test 将调用 toString。请参阅:

var myItem = {toString: function() { return 'foo'; }};

['foo', 'bar', 'baz'].indexOf(myItem); // -1
/^(foo|bar|baz)$/.test(myItem); // true

http://jsfiddle.net/hqu7D/

即使它们是字符串值(抱歉,错过了) )那么它们仍然不等价,因为有两种不同类型的字符串,并且indexOf使用严格的相等/同一性:

http://jsfiddle.net/HpCUY/

要使它们真正等效,您可以在使用 indexOf.toString() >,或者您可以在使用 test 之前测试 Object.prototype.toString.call(myItem) === '[object String]'

Okay, after the edit, they're still not equivalent since test will call toString. See:

var myItem = {toString: function() { return 'foo'; }};

['foo', 'bar', 'baz'].indexOf(myItem); // -1
/^(foo|bar|baz)$/.test(myItem); // true

http://jsfiddle.net/hqu7D/

Even when they're string values (sorry, missed that) then they're still not equivalent because there are two different types of strings and indexOf uses strict equality/identity:

http://jsfiddle.net/HpCUY/

To make them truly equivalent, you can either call .toString() before using indexOf, or you can test Object.prototype.toString.call(myItem) === '[object String]' before using test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文