$.each([collection]) 与 $([collection]).each() [英] $.each([collection]) vs $([collection]).each()

查看:19
本文介绍了$.each([collection]) 与 $([collection]).each()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法似乎产生相同的结果,但我很难真正说服人们第二种方法有效,因为它显然不为人所知.

Both methods appear to produce the same results, but I've been hard-pressed to actually convince people that the second method works, since it's apparently not commonly known.

// Create some data
var foo = { 'vals':[ {'id':'foo'}, {'id':'bar'} ] }​​​​​​​​​​​​​​​​​;

// Common Method    
$.each(foo.vals, function(i,o){
    alert(this.id);
});

// Alternative (lesser-known?) Method
$(foo.vals).each(function(i,o){
   alert(this.id); 
});

在检查来源后,这两者似乎是一回事.第二种方法如下:

Upon checking the source, these two appear to be one-in-the-same. The second method follows:

each: function( callback, args ) {
  return jQuery.each( this, callback, args );
}

这个方法显然调用了更常见的方法,这意味着它同样合法.这种理解是否正确,还是我在这里遗漏了什么?

This method demonstrably calls the more commonly-known method, meaning it's just as legitimate. Is this understanding correct, or am I missing something here?

我通常信任这种方法,因为它不会导致我在选择器方面偏离标准做法.让我们面对现实吧,我们受过训练:

I have typically trusted this method since it didn't cause me to deviate from standard practices with regards to selectors. Let's face it, we're trained to do:

$("p").each();

所以这样做似乎很自然:

So it seems only natural to do:

$(obj).each();

我错了吗?

推荐答案

两者之间的差异实际上是指数级的,具体取决于您使用它的方式.

The difference between the two is actually exponential depending on how you are using it.

第一个$.each 构成一个single 函数调用来启动迭代器.

The first $.each constitutes a single function call to start the iterator.

第二个$(foo.vals).each 调用三个 函数来启动迭代器.第一个是 $() ,它生成一个新的 jQuery 包装器集(不确定在此过程中进行了多少其他函数调用).然后调用$().each.最后它对 jQuery.each 进行内部调用以启动迭代器.

The second $(foo.vals).each makes three function calls to start the iterator. The first is to the $() which produces a new jQuery wrapper set (Not sure how many other function calls are made during this process). Then the call to $().each. And finally it makes the internal call to jQuery.each to start the iterator.

在您的示例中,至少可以说差异可以忽略不计.但是,在嵌套使用场景中,您可能会发现性能成为问题.

In your example, the difference would be negligible to say the least. However, in a nested use scenario, you might find performance becoming an issue.

最后,由于涉及函数调用,jQuery Enlightenment 中的 Cody Lindley 不建议将 $.each 用于大于 1000 次的迭代.使用普通的 for( var i = 0... 循环.

Finally, Cody Lindley in jQuery Enlightenment does not recommend using $.each for iterations greater than 1000 because of the function calls involved. Use a normal for( var i = 0... loop.

这篇关于$.each([collection]) 与 $([collection]).each()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆