我在使用 jsperf 时得到了一个非常有趣但绝对合乎逻辑的结果。
http://jsperf.com/for-in-jquery-return-value-vs-jquery-each
准备环境中,O
为200个DOM节点的jQuery返回值,a
为空数组,
O.each(function() {
a[a.length] = $(this).text();
});
比这个“纯”片段慢很多
for (i = 0; i < O.length; i++) {
a[a.length] = O[i].text();
}
(不同之处请查看上面的链接)
考虑到我只是玩得开心,必须有更快的方法。 使用 jQuery 遍历 DOM 元素的最快方法是什么?
最佳答案
又进行了一次测试,看来是
http://jsperf.com/for-in-jquery-return-value-vs-jquery-each/2
for (i = 0; i < O.length; i++) {
a[a.length] = O[i].text(); // tested this, because this is the usual way i work with pushing item to array
}
甚至比-
还快for (i = 0; i < O.length; i++) {
a.push($(O[i]).text());
}
我猜 push
本身比较慢,或者删除额外的 $(..)
会减少一些开销。
编辑:
关于javascript - 遍历 jQuery 返回的 DOM 节点的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24548993/