Fastest way to convert JavaScript NodeList to Array?

前端 未结 13 1696
清酒与你
清酒与你 2020-11-22 16:48

Previously answered questions here said that this was the fastest way:

//nl is a NodeList
var arr = Array.prototype.slice.call(nl);

In benc

相关标签:
13条回答
  • 2020-11-22 17:42

    The most fast and cross browser is

    for(var i=-1,l=nl.length;++i!==l;arr[i]=nl[i]);
    

    As I compared in

    http://jsbin.com/oqeda/98/edit

    *Thanks @CMS for the idea!

    Chromium (Similar to Google Chrome) Firefox Opera

    0 讨论(0)
  • 2020-11-22 17:43

    In ES6 you can either use:

    • Array.from

      let array = Array.from(nodelist)

    • Spread operator

      let array = [...nodelist]

    0 讨论(0)
  • 2020-11-22 17:44

    Assuming nodeList = document.querySelectorAll("div"), this is a concise form of converting nodelist to array.

    var nodeArray = [].slice.call(nodeList);
    

    See me use it here.

    0 讨论(0)
  • 2020-11-22 17:45

    The results will completely depend on the browser, to give an objective verdict, we have to make some performance tests, here are some results, you can run them here:

    Chrome 6:

    Firefox 3.6:

    Firefox 4.0b2:

    Safari 5:

    IE9 Platform Preview 3:

    0 讨论(0)
  • 2020-11-22 17:48

    With ES6, we now have a simple way to create an Array from a NodeList: the Array.from() function.

    // nl is a NodeList
    let myArray = Array.from(nl)
    
    0 讨论(0)
  • 2020-11-22 17:54

    Here's a new cool way to do it using the ES6 spread operator:

    let arr = [...nl];
    
    0 讨论(0)
提交回复
热议问题