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

时间:2017-11-14 11:04:11

标签: javascript react-native

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

 class NewsScreen extends React.Component {
     render() {
         this.organizationIDList = [];

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

2 个答案:

答案 0 :(得分:1)

使用arrow function

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

答案 1 :(得分:1)

使用如下箭头功能

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