首页 > 解决方案 > 比较两个数组并将结果推送到新数组

问题描述

我有两个完全用字符串填充的数组。我正在尝试比较字符串中的值,然后将字符串推送到一个空数组。

goupId = [
{'1','2','3','4'}]
homeGroups = 
[{'2','3', '4','1'}]
sameId =[];

这是我的逻辑

compare: function(groupId, homeGroups) {
                this.groupId.forEach((e1)=>this.homeGroups.foreach((e2)=>{
                    if(e1 === e2){
                        this.sameId.push(e1)
                    }
                }
            ));
            }

我收到错误 TypeError: Cannot read property 'forEach' of undefined"

标签: javascriptvue.js

解决方案


您需要this.在引用时删除它们groupIDhomeGroups因为它们不是成员变量。this 您可以在此处了解更多信息。

您的代码最终将如下所示。

compare: function(groupId, homeGroups) {
                groupId.forEach((e1)=>homeGroups.foreach((e2)=>{
                    if(e1 === e2){
                        this.sameId.push(e1)
                    }
                }
            ));
}

推荐阅读