Most efficient way to convert an HTMLCollection to an Array

前端 未结 7 2171
闹比i
闹比i 2020-11-22 13:10

Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an a

相关标签:
7条回答
  • 2020-11-22 13:30

    I saw a more concise method of getting Array.prototype methods in general that works just as well. Converting an HTMLCollection object into an Array object is demonstrated below:

    [].slice.call( yourHTMLCollectionObject );
    

    And, as mentioned in the comments, for old browsers such as IE7 and earlier, you simply have to use a compatibility function, like:

    function toArray(x) {
        for(var i = 0, a = []; i < x.length; i++)
            a.push(x[i]);
    
        return a
    }
    

    I know this is an old question, but I felt the accepted answer was a little incomplete; so I thought I'd throw this out there FWIW.

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