代码之家  ›  专栏  ›  技术社区  ›  RussellUresti

javascript性能-.test()与.search()。

  •  2
  • RussellUresti  · 技术社区  · 14 年前

    如果需要查看某个值是否在字符串中,使用.test()方法还是.search()方法对性能更好?

    .search()示例:

    var myRegExp = '/Orange/',
        myString = 'This is a string with the word "Orange."';
    
    if(myString.search(myRegExp) != -1) {
        // Do code here
    }
    

    .test()示例:

    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>
    

    因此,我要向列表项添加一个单击事件,如果它们的类名为“expanded”,则它们需要以某种方式工作;如果它们的类名为“expanded”,则它们需要以另一种方式工作。

    所以,从本质上来说,就是这样。

    element.addEventListener('click',function(e) {
        if( /* e.target has class name of expanded */ ) {
            // Do certain code
        } else {
            // Do other code
        }
    }
    

    我正在使用jquery,并且我乐于接受建议,但是我觉得这种情况最好使用原生的javascript。那么,哪种方法能提供最好的性能呢?或者还有其他更好的方法吗?

    3 回复  |  直到 10 年前
        1
  •  5
  •   lonesomeday    14 年前

    好吧,如果您使用的是jquery,那么只需

    element.addEventListener('click',function(e) {
        if( $(e.target).hasClass('expanded' ) {
            // Do certain code
        } else {
            // Do other code
        }
    }
    

    如果您出于任何原因(例如性能)不想创建jquery对象,那么可以使用此函数,该函数是根据 $().hasClass() :

    function hasClass ( el, selector ) {
        var className = " " + selector + " ";
    
        if ( (" " + el.className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1 ) {
            return true;
        }
    
        return false;
    }
    

    然后你可以这样称呼它:

    if ( hasClass(e.target, 'expanded') ) {
    

    就个人而言,如果您已经加载了jquery方法,我会选择它。

        2
  •  3
  •   mac    14 年前

    test()返回true或false。search()返回匹配项的位置,如果找不到匹配项,则返回-1。

    所以,我认为test()会更快。

        3
  •  0
  •   Community basarat    7 年前

    我也有同样的问题,在读了一些书之后,我发现使用本地字符串方法 indexOf 是从性能角度看最好的方法。这个 test 也证明了这一点。所以适当的方法是

    var searchStr = 'Orange',
        myString = 'This is a string with the world "Orange."';
    
    if(myString.indexOf(searchStr) != -1) {
        // Do code here
    }
    

    尽管这个问题有些老套,但仍然有用。我发现了 this question 也有很好的解释。