我非常喜欢在类似这样的节点列表上使用 forEach 方法:
var nodes = document.querySelectorAll(".foo");
[].forEach.call(nodes, function (item) {
//do stuff with item
});
我在想,这样做是否比常规方式花费更长时间? 例如:
for(var i=0;i<nodes.length;i++){
//do stuff with nodes[i];
}
我非常喜欢在类似这样的节点列表上使用 forEach 方法:
var nodes = document.querySelectorAll(".foo");
[].forEach.call(nodes, function (item) {
//do stuff with item
});
我在想,这样做是否比常规方式花费更长时间? 例如:
for(var i=0;i<nodes.length;i++){
//do stuff with nodes[i];
}
这里有一个关于性能比较的不错的比较。根据它的说法,Array.forEach
比本地的 for
循环更慢。
我知道这是个老帖子,但是通过窃取数组原型也可以使用forEach方法。
NodeList.prototype.forEach = Array.prototype.forEach;
这取决于浏览器。不要忘记在Firefox 4上while()是最快的。这里有一个比较。
还要记住,如果您支持不支持forEach的旧浏览器,则需要添加实现polyfill所需的时间。实现polyfill。
for(var i=0, el; el = nodes[i]; i++)
也可以工作 :) - salmatron