将 NodeList 视为数组的正确方法?
Proper way to treat NodeList as array?
好的,所以我知道 "proper" 方法使用 document.querySelectorAll(NodeList)的结果的传统智慧是通过使用类似的东西将其转换为数组:
Array.prototype.slice.call(elements)
但是,我一直在尝试将它们直接用作类似数组的对象,并且它似乎适用于以下结构:
document.querySelectorAll('selector').forEach(elem => console.log(elem.tagName));
我的问题是,使用这种更方便的语法会产生意想不到的后果吗?
Although NodeList
is not an Array
, it is possible to iterate over it with forEach()
. It can also be converted to a real Array
using Array.from()
.
However, some older browsers have not implemented NodeList.forEach()
nor Array.from()
. This can be circumvented by using Array.prototype.forEach()
— see this document's Example.
--- https://developer.mozilla.org/en-US/docs/Web/API/NodeList
除 IE 之外的所有浏览器都支持所有其他方法。因此使用起来比较安全。
NodeList 实现:
- [属性] 长度 - 与
array.length
相同
- [方法] 项 -
list.item(5) === list[5]
- [方法] forEach - 与
array.forEach
相同
- [METHOD] 条目 - 与
array.entries
相同
- [METHOD] 值 - 与
array.values
相同
- [METHOD] 键 - 与
array.keys
相同
根据规范,querySelectorAll
returns 一个 NodeList
, 只有 保证有它的元素和一个 length
属性。所以即使你的浏览器确实支持这个,这也是一个坏主意。如果您正在寻找更方便的语法,可以使用 Array.from
或扩展运算符:
Array.from(document.querySelectorAll('selector')).forEach()
[...document.querySelectorAll('selector')].forEach()
好的,所以我知道 "proper" 方法使用 document.querySelectorAll(NodeList)的结果的传统智慧是通过使用类似的东西将其转换为数组:
Array.prototype.slice.call(elements)
但是,我一直在尝试将它们直接用作类似数组的对象,并且它似乎适用于以下结构:
document.querySelectorAll('selector').forEach(elem => console.log(elem.tagName));
我的问题是,使用这种更方便的语法会产生意想不到的后果吗?
Although
NodeList
is not anArray
, it is possible to iterate over it withforEach()
. It can also be converted to a realArray
usingArray.from()
.However, some older browsers have not implemented
NodeList.forEach()
norArray.from()
. This can be circumvented by usingArray.prototype.forEach()
— see this document's Example.
--- https://developer.mozilla.org/en-US/docs/Web/API/NodeList
除 IE 之外的所有浏览器都支持所有其他方法。因此使用起来比较安全。
NodeList 实现:
- [属性] 长度 - 与
array.length
相同
- [方法] 项 -
list.item(5) === list[5]
- [方法] forEach - 与
array.forEach
相同
- [METHOD] 条目 - 与
array.entries
相同
- [METHOD] 值 - 与
array.values
相同
- [METHOD] 键 - 与
array.keys
相同
根据规范,querySelectorAll
returns 一个 NodeList
, 只有 保证有它的元素和一个 length
属性。所以即使你的浏览器确实支持这个,这也是一个坏主意。如果您正在寻找更方便的语法,可以使用 Array.from
或扩展运算符:
Array.from(document.querySelectorAll('selector')).forEach()
[...document.querySelectorAll('selector')].forEach()