Fastest way to convert JavaScript NodeList to Array?

前端 未结 13 1694
清酒与你
清酒与你 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:27

    faster and shorter :

    // nl is the nodelist
    var a=[], l=nl.length>>>0;
    for( ; l--; a[l]=nl[l] );
    
    0 讨论(0)
  • 2020-11-22 17:28

    Here are charts updated as of the date of this posting ("unknown platform" chart is Internet Explorer 11.15.16299.0):

    Safari 11.1.2 Firefox 61.0 Chrome 68.0.3440.75 Internet Explorer 11.15.16299.0

    From these results, it seems that the preallocate 1 method is the safest cross-browser bet.

    0 讨论(0)
  • 2020-11-22 17:29
    NodeList.prototype.forEach = Array.prototype.forEach;
    

    Now you can do document.querySelectorAll('div').forEach(function()...)

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

    This is the function I use in my JS:

    function toArray(nl) {
        for(var a=[], l=nl.length; l--; a[l]=nl[l]);
        return a;
    }
    
    0 讨论(0)
  • 2020-11-22 17:37

    Some optimizations:

    • save the NodeList's length in a variable
    • explicitly set the new array's length before setting.
    • access the indices, rather than pushing or unshifting.

    Code (jsPerf):

    var arr = [];
    for (var i = 0, ref = arr.length = nl.length; i < ref; i++) {
     arr[i] = nl[i];
    }
    
    0 讨论(0)
  • 2020-11-22 17:38

    The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'

    @kangax (IE 9 preview)

    Array.prototype.slice can now convert certain host objects (e.g. NodeList’s) to arrays — something that majority of modern browsers have been able to do for quite a while.

    Example:

    Array.prototype.slice.call(document.childNodes);
    
    0 讨论(0)
提交回复
热议问题