Home > Web Front-end > JS Tutorial > How to Efficiently Convert an HTMLCollection to an Array in JavaScript?

How to Efficiently Convert an HTMLCollection to an Array in JavaScript?

Barbara Streisand
Release: 2024-11-19 18:12:03
Original
631 people have browsed it

How to Efficiently Convert an HTMLCollection to an Array in JavaScript?

Efficient Conversion of HTMLCollection to Array

Converting an HTMLCollection, a collection of elements in an HTML document, to an array is a common task in web development. While iterating and manually copying each item into an array works, it can be inefficient.

"Native" Code Solution

A more efficient approach is to use the native JavaScript method Array.prototype.slice.call():

var arr = Array.prototype.slice.call(htmlCollection);
Copy after login

This method returns an array containing the elements from the htmlCollection object.

Concise Expression

Since the syntax can be verbose, a more concise equivalent expression is:

var arr = [].slice.call(htmlCollection);
Copy after login

ES6 Solutions

ES6 (ECMAScript 2015) introduced additional options:

  • Array.from(): Converts an iterable object, such as an HTMLCollection, to an array.
var arr = Array.from(htmlCollection);
Copy after login
  • Spread Operator: Unpacks an iterable object into an array.
var arr = [...htmlCollection];
Copy after login

Performance Comparison

Benchmarks (e.g., https://jsben.ch/h2IFA) show that the following methods have similar performance:

  • Array.prototype.slice.call()
  • [].slice.call()
  • Array.from()

The spread operator is slightly slower, but it may be preferred for its concise syntax.

Therefore, the most efficient way to convert an HTMLCollection to an array depends on the specific requirements and preferences of the developer.

The above is the detailed content of How to Efficiently Convert an HTMLCollection to an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template