RegExp 等价于 array.indexOf( str )
给定一个包含字符串值的变量 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不完全是。管道包括
^
和$
作为替代。我不太清楚 JS 正则表达式的语法,但是如果您正在寻找仅包含foo
或bar
的str
或baz
,使用表达式/^(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 forstr
to contain onlyfoo
, orbar
, orbaz
, 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.不,他们不是。
方法
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
returnstrue
if the regex finds a match, andfalse
if it doesn't.If your regular expression was instead
/^(foo|bar|baz)$/
, then the function would be the same.好的,编辑后,它们仍然不等效,因为
test
将调用toString
。请参阅: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 calltoString
. See: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 usingindexOf
, or you can testObject.prototype.toString.call(myItem) === '[object String]'
before usingtest
.