First option: invoke forEach indirectly
parent.children
是一个类似数组的对象.使用以下解决方案:
const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
parent.children
是NodeList
类型,这是一个类似数组的对象,因为:
- 它包含
length
属性,该属性指示 node 数
- 每个 node 都是一个具有数字名称的属性值,从0:
{0: NodeObject, 1: NodeObject, length: 2, ...}
开始
请在this article中查看更多详细信息.
Second option: use the iterable protocol
parent.children
是一个HTMLCollection
:它实现了iterable protocol.在ES2015环境中,您可以将HTMLCollection
与任何可接受iterables的构造一起使用.
将HTMLCollection
与排列操纵器一起使用:
const parent = this.el.parentElement;
[...parent.children].forEach(child => {
console.log(child);
});
或者使用for..of
循环(这是我的首选选项):
const parent = this.el.parentElement;
for (const child of parent.children) {
console.log(child);
}