Speed of [].forEach.call(…?

后端 未结 3 1886
生来不讨喜
生来不讨喜 2021-01-01 00:53

I\'m a big fan of using the forEach method on nodeLists like this:

var nodes = document.querySelectorAll(\".foo\");

[].forEach.call(nodes, function (item) {         


        
相关标签:
3条回答
  • 2021-01-01 01:17

    I know it's an old post but using the forEach method can be done by stealing the Array prototype as well.

    NodeList.prototype.forEach = Array.prototype.forEach;
    
    0 讨论(0)
  • 2021-01-01 01:29

    It depends on the browser. And don't forget about while() which is the fastest on Firefox 4. Here's a comparison.

    Also keep in mind that if you're supporting older browsers that don't support forEach, you need to add in the time it takes to implement a polyfill.

    0 讨论(0)
  • 2021-01-01 01:43

    Here's a nice performance comparison. According to it Array.forEach is slower than a native for loop.

    0 讨论(0)
提交回复
热议问题