The Most Efficient Approach to Convert a JavaScript NodeList to an Array
Despite previous suggestions claiming the use of Array.prototype.slice.call(nl) as the most efficient method, recent benchmarks have revealed that a simpler approach outperforms it significantly.
Alternative Approach:
var arr = []; for(var i = 0, n; n = nl[i]; ++i) arr.push(n);
Surprisingly, this loop-based approach proves to be more than three times faster than the previously recommended method.
ES6 Solution:
With the advent of ES6, a more straightforward solution has emerged: the Array.from() function. It effortlessly converts a NodeList to an Array with the following syntax:
let myArray = Array.from(nl);
This approach offers both simplicity and efficiency, making it the preferred choice for converting NodeLists to Arrays.
The above is the detailed content of Which is the Most Efficient Way to Convert a JavaScript NodeList to an Array?. For more information, please follow other related articles on the PHP Chinese website!