如何在 Javascript 中从 foreach 访问类变量



我想将数据推送到this.organizationIDList .我在推送时遇到未定义的错误。如何将数据推送到该变量?

 class NewsScreen extends React.Component {
     render() {
         this.organizationIDList = [];
         this.organizations.forEach(function (organization) {
             this.organizationIDList.push(organization.id);
         });
     }
 }

使用箭头函数

            this.organizations.forEach((organization) => {
                this.organizationIDList.push(organization.id);
            });

或者this传递给接受thisArg的forEach

            this.organizations.forEach(function (organization) {
                this.organizationIDList.push(organization.id);
            }, this);

上面的代码也可以写成:

this.organizationIdList = this.organizations.map(organization =>organization.id);

使用如下所示的箭头函数

this.organizations.forEach((organization) => {
   this.organizationIDList.push(organization.id);
});

相关内容

  • 没有找到相关文章

最新更新