Javascript 如何在javascript中将集合转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5158338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a collection to an array in javascript
提问by wajiw
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.
我试图弄清楚如何将 javascript 集合(即从 getElementsByTagName/etc 返回的内容)转换为普通数组,以便我可以对数据执行数组函数。
I'm looking for a solution withoutusing any libraries and haven't been able to find any sort of elegant solutions anywhere online. Has anyone written a good util function for this problem?
我正在寻找一个不使用任何库的解决方案,并且无法在网上的任何地方找到任何优雅的解决方案。有没有人为这个问题写过一个好的 util 函数?
回答by user113716
You can do this:
你可以这样做:
var coll = document.getElementsByTagName('div');
var arr = Array.prototype.slice.call( coll, 0 );
EDIT:As @Chris Nielsennoted, 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) solutionfrom @brilliand.
编辑:正如@Chris Nielsen 所指出的,这在 IE 9 之前失败了。最好是做一些功能测试,并创建一个可以处理任何一种,或者只是做一个循环中的函数(第二)解决方案从@brilliand。
回答by sqren
In modern browser you can use Array.from
which "creates a new Array instance from an array-like or iterable object"
在现代浏览器中,您可以使用Array.from
which “从类数组或可迭代对象创建新的 Array 实例”
Example: Convert an HTML collection to array
示例:将 HTML 集合转换为数组
const divs = document.getElementsByTagName('div');
const myArray = Array.from(divs); // [div, div, ...]
回答by Brilliand
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:
自从我使用 JavaScript 以来已经有一段时间了......你可能需要这个:
var coll = document.getElementsByTagName('div');
var arr = [];
for(var i = 0; i < coll.length; i++) arr.push(coll[i]);
回答by Jiml
You can use spread operator:
您可以使用扩展运算符:
var coll = document.getElementsByTagName('div');
var arr = [...coll];