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 array?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
will have the same effect using ‘native’ code.
Edit
Since this gets a lot of views, note (per @oriol’s comment) that the following more concise expression is effectively equivalent:
But note per @JussiR’s comment, that unlike the ‘verbose’ form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer’s ken.
Edit
Since ECMAScript 2015 (ES 6) there is also Array.from:
Edit
ECMAScript 2015 also provides the spread operator, which is functionally equivalent to
Array.from(although note thatArray.fromsupports a mapping function as the second argument).I’ve confirmed that both of the above work on
NodeList.A performance comparison for the mentioned methods: http://jsben.ch/h2IFA