在 Javascript 中,将 NodeList 转换为数组的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7459704/
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
In Javascript, what is the best way to convert a NodeList to an array
提问by cc young
The DOM method document.querySelectorAll()
(and a few others) return a NodeList
.
DOM 方法document.querySelectorAll()
(以及其他一些方法)返回一个NodeList
.
To operate on the list, e.g. using forEach()
, the NodeList
must first be converted to an Array
.
要对列表进行操作,例如 using forEach()
,NodeList
必须首先将 转换为Array
。
What's the best way to convert the NodeList
to an Array
?
将 the 转换NodeList
为 an的最佳方法是Array
什么?
采纳答案by Freezystem
With ES6 you can simply do:
使用 ES6,您可以简单地执行以下操作:
const spanList = [...document.querySelectorAll("span")];
回答by sandstrom
With ES6 you can use Array.from(myNodeList)
. Then use your favourite array method.
在 ES6 中,您可以使用Array.from(myNodeList)
. 然后使用您最喜欢的数组方法。
var myNodeList = document.querySelectorAll('.my-selector');
// ALT 1
Array.from(myNodeList).forEach(function(el) {
console.log(el);
});
Use an ES6 shimto make this work in older browsers too.
使用ES6 shim也可以在较旧的浏览器中执行此操作。
If you are using a transpiler (for example Babel) there are two more alternatives:
如果您使用的是转译器(例如 Babel),还有两种选择:
var myNodeList = document.querySelectorAll('.my-selector');
// ALT 2
for (var el of myNodeList) {
el.classList.add('active'); // or some other action
}
// ALT 3
[...myNodeList].forEach((el) => {
console.log(el);
});
回答by Joseph Silber
You can convert it to an array by using the slice
method from the Array
prototype:
您可以使用原型中的slice
方法将其转换为数组Array
:
var elList = document.querySelectorAll('.viewcount');
elList = Array.prototype.slice.call(elList, 0);
Furthermore, if all you need is forEach
, you can invoke thatfrom the Array
prototype, without coercing it to an array first:
此外,如果您只需要forEach
,则可以从原型中调用它Array
,而无需先将其强制为数组:
var elList = document.querySelectorAll('.viewcount');
Array.prototype.forEach.call(elList, function(el) {
console.log(el);
});
In ES6, you can use the new Array.from
function to convert it to an array:
在 ES6 中,您可以使用新Array.from
函数将其转换为数组:
Array.from(elList).forEach(function(el) {
console.log(el);
});
This is currently only in bleeding edge browsers, but if you're using a polyfill serviceyou will have access to this function across the board.
这目前仅适用于前沿浏览器,但如果您使用的是 polyfill 服务,您将可以全面访问此功能。
If you're using an ES6 transpiler, you can even use a for..of
loop instead:
如果您使用的是 ES6 转译器,您甚至可以使用for..of
循环:
for (var element of document.querySelectorAll('.some .elements')) {
// use element here
}
回答by c69
Why convert? - just call
function of Array directly on element collection ;)
为什么要转换?- 只是call
直接在元素集合上的 Array 函数;)
[].forEach.call( $('a'), function( v, i) {
// do something
});
assuming $is your alias for querySelectorAll, of course
当然,假设$是querySelectorAll的别名
edit: ES6 allows for even shorter syntax [...$('a')]
(works in Firefox only, as of May 2014)
编辑:ES6 允许更短的语法[...$('a')]
(仅适用于 Firefox,截至 2014 年 5 月)
回答by nfechner
Does it have to be forEach
? You could simply use a for
loop to iterate over the list:
必须是forEach
吗?您可以简单地使用for
循环来遍历列表:
for (var i = 0; i < elementList.length; i++) {
doSomethingWith(elementlist.item(i));
}
回答by mikemaccana
To operate on the list in javascript, e.g. using forEach(), the NodeList must be converted to an Array.
要在javascript 中对列表进行操作,例如使用forEach(),必须将NodeList 转换为数组。
That's not necessarily true. You can add .forEach() from Arrayto NodeListand it works fine:
这不一定是真的。您可以将 .forEach() 从Array添加到NodeList并且它工作正常:
if ( ! NodeList.prototype.forEach ) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
You can now run:
您现在可以运行:
myNodeList.forEach(function(node){...})
To iterate over NodeLists just like Arrays.
像数组一样遍历 NodeList。
This produces much shorter and cleaner code than .call() everywhere.
这会产生比 .call() 任何地方都更短、更干净的代码。
回答by Redu
ES6 allows cool ways like var nodeArray = Array.from(nodeList)
but my favorite one is the new spread operator.
ES6 允许很酷的方式,var nodeArray = Array.from(nodeList)
但我最喜欢的是新的传播运算符。
var nodeArray = Array(...nodeList);
回答by brad
I use the following because I think it's easiest to read:
我使用以下内容是因为我认为它最容易阅读:
const elements = document.getElementsByClassName('element');
[...elements].forEach((element) => {
// code
});
回答by Amr.Ayoub
That worked with me in ES6
在 ES6 中对我有用
lets assume you have nodelist like that
让我们假设你有这样的节点列表
<ul>
<li data-time="5:17">Flexbox video</li>
<li data-time="8:22">Flexbox video</li>
<li data-time="3:24">Redux video</li>
<li data-time="5:17">Flexbox video</li>
<li data-time="7:17">Flexbox video</li>
<li data-time="4:17">Flexbox video</li>
<li data-time="2:17">Redux video</li>
<li data-time="7:17">Flexbox video</li>
<li data-time="9:54">Flexbox video</li>
<li data-time="5:53">Flexbox video</li>
<li data-time="7:32">Flexbox video</li>
<li data-time="2:47">Redux video</li>
<li data-time="9:17">Flexbox video</li>
</ul>
const items = Array.from(document.querySelectorAll('[data-time]'));
console.log(items);
回答by Per Quested Aronsson
Assuming elemsis a nodeList:
假设elems是一个 nodeList:
var elems = document.querySelectorAll('select option:checked');
then it can be turned into an array as follows:
那么它可以变成一个数组,如下所示:
var values = [].map.call(elems, function(obj) {
return obj.value;
});
参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Example: _using_map_genericically_querySelectorAll