Home > Article > Web Front-end > How to Efficiently Convert an HTMLCollection to an Array?
Converting an HTMLCollection to an array can be achieved through iterative means, appending each item to an array manually. However, there are more efficient approaches to this conversion.
Native Code Approach:
One such approach utilizes the slice method of the Array.prototype, as exemplified by the following code snippet:
var arr = Array.prototype.slice.call(htmlCollection);
This method effectively emulates the functionality of the iterative iteration, providing an efficient means of conversion.
Concise Version:
For greater brevity, the expression below achieves the same result:
var arr = [].slice.call(htmlCollection);
Array.from (ES6 ):
In ECMAScript 2015 and later versions, the Array.from method offers a native solution for converting iterable objects to arrays, including HTMLCollections:
var arr = Array.from(htmlCollection);
Spread Operator (ES6 ):
The spread operator, introduced in ES6, provides a functionally equivalent method to Array.from, as illustrated below:
var arr = [...htmlCollection];
Performance Comparison:
For comparative analysis of these methods, refer to the following benchmark: http://jsben.ch/h2IFA
The above is the detailed content of How to Efficiently Convert an HTMLCollection to an Array?. For more information, please follow other related articles on the PHP Chinese website!