【问题标题】:Replacing jQuery each with for用 for 替换每个 jQuery
【发布时间】:2010-11-24 12:01:06
【问题描述】:

我已经使用 $.each 进行迭代有一段时间了,但我不断听到人们说要使用原生 JS 来进行循环。我非常关心性能,但我不确定是否总是可以以有意义的方式将 $.each 替换为 for。

所以我的问题是,是否可以始终将 $.each 替换为 for,如果不是,那么经验法则是什么时候可以做到,什么时候不能做到。

我有一个这样的:

 $this.find("div.class").each(function (){
  var $thisparent = $(this).parent();

  if (condition) {          
   $(this).prepend($thisparent.text());
  }

  if (condition2) {          
   $(this).prepend($thisparent.text());
  }

 });

【问题讨论】:

    标签: javascript jquery for-loop each


    【解决方案1】:

    这就是 jQuery 对 .each 所做的,基本上

    $.fn.each = function(callback) {
        var i, length = this.length;
        for(i = 0; i < length; ++i) {
            callback.call(this[i]);
        }
    };
    

    因此,将匿名函数的“内容”替换为 callback.call 调用并不难。请务必将 this 替换为带有 jQ​​uery 对象的临时对象。

    转换您提供的代码:

    var foo = $this.find("div.class"),
        fooLength = foo.length,
        i,
        $thisparent;
    
    for (i = 0; i < fooLength; ++i) {
        $thisparent = $(foo[i]).parent();
    
        if (condition) {          
            $(foo[i]).prepend($thisparent.text());
        }
    
        if (condition2) {          
            $(foo[i]).prepend($thisparent.text());
        }
    }
    

    为了提高(潜在)速度,将foo[i] 缓存到临时文件中。也,仅在需要时分配$thisparent。如果conditioncondition2 互斥,则使用单个if (condition || condition2)

    【讨论】:

    • 非常感谢,您能举个例子吗?谢谢。
    • 非常感谢,:) 很好的回答,感谢您增加我的理解。你能演示如何使用单个 if 吗?另外,如果我有六个互斥条件怎么办。
    【解决方案2】:

    【讨论】:

    • 所以显然你只会对大型阵列造成实质性的性能影响。很高兴知道。
    • 我认为这背后的原因是函数调用的开销,因为 jQuery 的 each 代码一点也不重。
    • @Joel:嗯,从某种意义上说,jQuery 需要两倍的时间(数组大小为一百万),这很重要。但差别只有 600 毫秒,真的没什么。
    • 但我们都知道:许多混蛋会变成混蛋。 ^^
    • @anddoutoi - +1 表示“很多人都会做事”
    猜你喜欢
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 2016-06-16
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    相关资源
    最近更新 更多