作为JavaScript的新手,我不知道什么时候使用它们。

有人能帮我解释一下吗?


当前回答

除了已经提到的所有其他注意事项,indexOf在很大程度上更快,如果你不需要做时髦的正则表达式,只是做一个简单的查找,那么不要使用搜索。 robisrob想要一些证据,所以我做了一个快速测试。

Starting...
  IndexOf test - loop count 10000000
  IndexOf test end - duration: 4.600000023841858ms
  Search test - loop count 10000000
  Search test end - duration: 1221.6999999284744ms
All Done

这是一个显著的区别,只有当你要使用正则表达式时才使用搜索。

如果有人感兴趣,我可以发布测试代码。

其他回答

我认为主要的区别是搜索接受正则表达式。

检查一下参考资料:

搜索 indexOf

搜索函数(这里的一个描述)接受一个正则表达式,它允许您匹配更复杂的模式、不区分大小写的字符串等,而indexOf(这里的一个描述)只匹配文字字符串。但是,indexOf还允许指定开始索引。

如果没有正则表达式,indexOf和search之间就没有实际的区别。

下面的例子给出了一个现场演示:

function FromSearch() { var str = document.getElementById("demo").innerText; var n = str.search("difference"); document.getElementById("Location").innerHTML = n; } function FromindexOf() { var str = document.getElementById("demo").innerText; var n = str.indexOf("difference"); document.getElementById("Location").innerHTML = n; } <p id="demo">Without a <a href='http://www.w3schools.com/js/js_regexp.asp'>regex</a>, there is no practical difference between <a href='http://www.w3schools.com/jsref/jsref_indexof.asp'>indexOf</a> and <a href='http://www.w3schools.com/jsref/jsref_search.asp'>search</a> </p> <button onclick="FromSearch()">From search</button> <button onclick="FromindexOf()">From indexOf</button> <p>Location of difference in the above sentence is:</p> <mark id="Location"></mark>

如果您的情况需要使用正则表达式,则使用search()方法,否则;indexOf()方法性能更好。

indexOf()和search()

两者都有 I)返回第一个出现的搜索值 Ii)如果没有找到匹配则返回-1 让str='书已预订交付' str.indexOf('b') //返回位置8 Str.search ('b') //返回位置8


indexOf()中的特殊值 I)你可以把起始搜索位置作为第二个参数 str.indexOf('k') // 3 str.indexOf('k',4) // 11(从第4个位置开始搜索)


特殊搜索()

搜索值可以是正则表达式

str.search('book') // 8
str.search(/book/i)  // 0   ( /i =case-insensitive   (Book == book)

参考