简体   繁体   English

在 JavaScript 中,将 NodeList 转换为数组的最佳方法是什么?

[英]In JavaScript, what is the best way to convert a NodeList to an array?

The DOM method document.querySelectorAll() (and a few others) return a NodeList . DOM 方法document.querySelectorAll() (以及其他一些方法)返回一个NodeList

To operate on the list, eg using forEach() , the NodeList must first be converted to an Array .要对列表进行操作,例如使用forEach() ,必须首先将NodeList转换为Array

What's the best way to convert the NodeList to an Array ?NodeList转换为Array的最佳方法是什么?

使用 ES6,您可以简单地执行以下操作:

const spanList = [...document.querySelectorAll("span")];

With ES6 you can use Array.from(myNodeList) .在 ES6 中,您可以使用Array.from(myNodeList) Then use your favourite array method.然后使用您最喜欢的数组方法。

var myNodeList = document.querySelectorAll('.my-selector');

// ALT 1
Array.from(myNodeList).forEach(function(el) {
  console.log(el);
});

Use an ES6 shim to 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);
});

You can convert it to an array by using the slice method from the Array prototype:您可以使用Array原型中的slice方法将其转换为数组:

var elList = document.querySelectorAll('.viewcount');
elList = Array.prototype.slice.call(elList, 0);

Furthermore, if all you need is forEach , you can invoke that from 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 service you 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
}

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 月

2020 update: nodeList.forEach() is now an official standard and supported in all current browsers. 2020 年更新: nodeList.forEach() 现在是官方标准,并在所有当前浏览器中受支持。

Older browsers can use the polyfill below.较旧的浏览器可以使用下面的 polyfill。

To operate on the list in javascript, eg using forEach(), the NodeList must be converted to an Array.要在javascript 中对列表进行操作,例如使用forEach(),必须将NodeList 转换为数组。

That's not true.这不是真的。 .forEach() works in current browsers. .forEach()适用于当前浏览器。 If it's missing, you can use a polyfill to add .forEach() from Array to NodeList and it works fine:如果缺少,您可以使用 polyfill 将 .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() 任何地方都更短、更干净的代码。

Does it have to be forEach ?它必须是forEach吗? You could simply use a for loop to iterate over the list:您可以简单地使用for循环遍历列表:

for (var i = 0; i < elementList.length; i++) {
    doSomethingWith(elementlist.item(i));
}

Well, this works for me too:嗯,这也适用于我:

const elements = Object.values( document.querySelector(your selector here) )

Object.values() returns Array of values of given object. Object.values()返回给定对象的值Array NodeList is object, as is everything in JS. NodeList是对象,就像 JS 中的一切一样。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

But it's not compatible with IE, so i guess Array.prototype.*array_method*.call(yourNodeList) is the best option.但它与 IE 不兼容,所以我猜Array.prototype.*array_method*.call(yourNodeList)是最好的选择。 With this you can invoke any array method on your NodeList有了这个,您可以调用NodeList上的任何数组方法

ES6 允许像var nodeArray = Array.from(nodeList)这样很酷的方法,但我最喜欢的方法是新的传播运算符。

var nodeArray = Array(...nodeList);

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);

I use the following because I think it's easiest to read:我使用以下内容是因为我认为它最容易阅读:

const elements = document.getElementsByClassName('element');
[...elements].forEach((element) => {
   // code
});

打字稿版本:

const allDayElements: Element[] = [].slice.call(document.querySelectorAll('span'));

Assuming elems is 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;
});

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Example:_using_map_generically_querySelectorAll参考: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Example : _using_map_genericically_querySelectorAll

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM