这些主要是我一直在想的一些事情,也许有人能给我一些更多的洞察力,我也会分享我到目前为止注意到的东西!

First thing i've been wondering... is there any difference good or reason to use:

$('element').each(function (i, el) { });

-- versus --

$.each($('element'), function (i, el) { });

Looking at the jQuery docs I can't see any rhyme or reason for one or the other (maybe you know an instance or additional things one can do over the other.

But more importantly I'm concerned with speed here

// As opposed to $.each() looping through a jQuery object
// -- 8x faster 
for (var i = 0, $('.whatever').length; i < len; i++) {
    $('.whatever')[i] // do stuff
}

如果你看一下这个100,你会发现速度上的差异基本上等同于他们中的任何一个,但更重要的是,我觉得always应该使用for()个循环……

我只是单元测试(循环5个不同的场景函数,50000次),简单地循环一系列列表项,设置data-newAttr,没什么特别的.


QUESTION :: I guess my biggest question is, why not always use for loops while iterating through an object?? Is there even a point to using $.each()? Do you always use for() loops even when going through jQuery objects?

jsFiddle DEMO here

Function type:                  Execution Time:
_testArea.each() + $(this)               1947   <-- using $(this) slows it down tremendously
$.each()         + $(this)               1940
_testArea.each() + el(plain JS)           458   <-- using the Element speeds things up
$.each()         + el(plain JS)           452
for() loop       + plainJS[0] iteration   236   <-- over 8x faster

只有我的两个儿子.:)

推荐答案

One thing that .each() allows you to do that can't be done with a for loop is chaining.

$('.rows').each(function(i, el) {
    // do something with ALL the rows
}).filter('.even').each(function(i, el) {
    // do something with the even rows
});

I played around with your JSFiddle查看在必须循环遍历原始匹配元素集的子集的情况下,链接将如何影响性能.

结果并不是那么出人意料,尽管我认为end()的开销在这里被夸大了,因为元素少,循环多.除此之外:普通JS循环的速度仍然稍快,但这是否能达到.each()(和链接)的可读性还存在争议.

Jquery相关问答推荐

使用 shell 脚本判断 json 数组响应是否具有特定用户名和状态的 jq 命令

如果选中了三个sibling ,则选中一个复选框

为什么在 jQuery 插件中返回 this.each(function())?

Bootstrap 4 多选下拉菜单

Bootstrap 3 RC 1 中的 typeahead JavaScript 模块在哪里?

如何判断输入日期是否等于今天的日期?

JQuery html() 与 innerHTML

如何使用 jQuery 进行带命名空间的 XML 解析

模态窗口中的 Twitter Bootstrap Datepicker

专业的基于 jQuery 的 Combobox 控件?

带有 jquery 的 jsonp

C# String.IsNullOrEmpty Javascript 等效项

jQuery闪烁突出显示对div的影响?

延迟jquery悬停事件?

jQuery.active 函数

获取jQuery中下拉列表的值

在 Firefox 上开发的 Javascript 在 IE 上失败的典型原因是什么?

jQuery向左滑动并显示

Jquery 日期 Select 器 z-index 问题

使用 jQuery 将一个标签替换为另一个标签