Mar*_*ark 10 javascript each jquery for-loop
我一直在使用$ .each进行迭代一段时间,但我一直听到有人说使用原生JS来做循环.我非常关心性能,但我不确定是否总能以有意义的方式替换$ .each.
所以我的问题是,是否有可能总是用$替换$ .each,如果不是,那么什么时候可以做到以及什么时候做不到的经验.
我有一个这样的人:
$this.find("div.class").each(function (){
var $thisparent = $(this).parent();
if (condition) {
$(this).prepend($thisparent.text());
}
if (condition2) {
$(this).prepend($thisparent.text());
}
});
Run Code Online (Sandbox Code Playgroud)
这就是jQuery所做的.each,基本上:
$.fn.each = function(callback) {
var i, length = this.length;
for(i = 0; i < length; ++i) {
callback.call(this[i]);
}
};
Run Code Online (Sandbox Code Playgroud)
因此,通过callback.call调用替换匿名函数的"内容"并不难.请务必this使用jQuery对象替换临时对象.
转换您提供的代码:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
对于其他(潜在)速度,缓存foo[i]为临时.也是,$thisparent只在需要时分配.如果condition并且condition2是互斥的,请使用单个if (condition || condition2).
有人比较了for和的表现$.each:
http://jquery-howto.blogspot.com/2009/06/javascript-for-loop-vs-jquery-each.html