如果我需要查看某個值是否在字符串中,那麼使用.test()方法或.search()方法的性能會更好嗎?JavaScript性能 - .test()與.search()
例如使用.search():
var myRegExp = '/Orange/',
myString = 'This is a string with the word "Orange."';
if(myString.search(myRegExp) != -1) {
// Do code here
}
例如使用。測試():
var myRegExp = '/Orange/',
myString = 'This is a string with the world "Orange."';
if(myRegExp.test(myString)) {
// Do code here
}
最終,我做的是搜索字符串中的一個特定的類名。該元素將包含多個類,所以我需要找出是否有其中一個類。
示例標記:
<ul>
<li class="expandable expanded">
<ul>
<li>Text</li>
</ul>
<li>
<li class="expandable collapsed">
<ul>
<li>Text</li>
</ul>
</li>
</ul>
所以,我加入一個click事件列表中的項目,如果他們有類名「擴展」他們需要表現的一種方式,如果他們有類名「崩潰」他們需要表現另一個。
所以,基本上是這樣的。
element.addEventListener('click',function(e) {
if(/* e.target has class name of expanded */) {
// Do certain code
} else {
// Do other code
}
}
我使用的是jQuery,我很樂意提供建議,但我覺得這種情況會更好地與本機JavaScript。那麼,哪種方法可以提供最佳性能?或者還有另一種更好的方法嗎?
http://jsperf.com/ – 2010-10-12 19:04:05