开发者

How to convert a collection to an array in javascript

开发者 https://www.devze.com 2023-02-14 17:09 出处:网络
I\'m trying to figure out how to convert a javascript collection (i.e. something returned from getElementsByTagName/etc) to a normal array so I can perform array functions on the data.

I'm trying to figure out how to convert a javascript collection (i.e. something returned from getElementsByTagName/etc) to a normal array so I can perform array functions on the data.

I'm looking for a solution without using any libraries and haven't been able to find any sort of elegant solutions anywhere online. Has anyo开发者_JS百科ne written a good util function for this problem?


You can do this:

var coll = document.getElementsByTagName('div');

var arr = Array.prototype.slice.call( coll, 0 );

EDIT: As @Chris Nielsen noted, this fails in IE pre-9. Best would be to do some feature testing, and create a function that can handle either, or just do a loop as in the (second) solution from @brilliand.


This has become a lot simpler in modern browsers. I'll outline two approaches.

Spread operator

"Spread syntax allows an iterable (...) to be expanded"

const divs = document.getElementsByTagName('div');
const myArray = [...divs]; // [div, div, ...]

Array.from

Array.from "creates a new Array instance from an array-like or iterable object"

Example: Convert an HTML collection to array

const divs = document.getElementsByTagName('div');
const myArray = Array.from(divs); // [div, div, ...]


Copy it to a regular array?

var coll = document.getElementsByTagName('div');
var arr = [];
for(var i in coll) arr[i] = coll[i];

Been a while since I used JavaScript... you may need this instead:

var coll = document.getElementsByTagName('div');
var arr = [];
for(var i = 0; i < coll.length; i++) arr.push(coll[i]);


You can use spread operator:

var coll = document.getElementsByTagName('div');

var arr = [...coll];

Spread syntax

0

精彩评论

暂无评论...
验证码 换一张
取 消