作为JavaScript的新手,我不知道什么时候使用它们。
有人能帮我解释一下吗?
作为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
这是一个显著的区别,只有当你要使用正则表达式时才使用搜索。
如果有人感兴趣,我可以发布测试代码。
其他回答
如果您的情况需要使用正则表达式,则使用search()方法,否则;indexOf()方法性能更好。
IndexOf() -它接受字符串字面量或字符串对象,但不接受正则表达式。它还接受一个从零开始的整数值来开始搜索,例如:
“babyelephant .indexOf(“e”);//得到4 “babyelephant .indexOf(“e”,5);//搜索结果为6 从第6个位置或第5个索引开始。 Var m= /e/;“babyelephant .indexOf (m);//给出-1,因为它没有 接受正则表达式。
Search() -接受字符串字面量或字符串对象和正则表达式。但是它不接受开始搜索的索引。
indexOf用于普通子字符串,search用于正则表达式。
如果没有正则表达式,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>
搜索发现它与正则表达式匹配,但没有偏移量。IndexOf使用字面量进行匹配,但有一个偏移量。
IndexOf
搜索