我试着做一个简单的循环:

const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
  console.log(child)
})

但我得到了以下错误:

VM384:53未捕获类型错误:父级. children forEach不是一个函数

尽管有parent.children个日志(log):

enter image description here

有什么问题吗?

注:这是JSFiddle美元.

推荐答案

First option: invoke forEach indirectly

parent.children是一个类似数组的对象.使用以下解决方案:

const parent = this.el.parentElement;

Array.prototype.forEach.call(parent.children, child => {
  console.log(child)
});

parent.childrenNodeList类型,这是一个类似数组的对象,因为:

  • 它包含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);
}

Javascript相关问答推荐

Webpack将懒惰加载的模块放入主块中

访客柜台的风格React.js

如何在非独立组件中使用独立组件?

Flisk和JS错误:未捕获的Syntax错误:意外的令牌'<'

Express.js:使用Passport.js实现基于角色的身份验证时出现太多重定向问题

仅在React和JS中生成深色

React Hooks中useState的同步问题

将数据从strapi提取到next.js,但响应延迟API URL

Javascript,部分重排序数组

Chrome是否忽略WebAuthentication userVerification设置?""

如何将Openjphjs与next.js一起使用?

无法访问Vue 3深度监视器中对象数组的特定对象值'

Angular 中的类型错误上不存在获取属性

在VS代码上一次设置多个变量格式

如何在HTMX提示符中设置默认值?

Next.js中的服务器端组件列表筛选

无法检索与Puppeteer的蒸汽游戏的Bundle 包价格

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

用另一个带有类名的div包装元素

为什么我不能使用其同级元素调用和更新子元素?