forEach Typescript TS2339“;不存在于类型';无效'&引用;

forEach Typescript TS2339“;不存在于类型';无效'&引用;,typescript,Typescript,试图找到两个数组的交集,为什么我得到的是TS2339:类型“void”上不存在属性“collection” 所有数组都在同一个类中声明 this.locations.forEach(function(location) { this.collection.locations.forEach(function(id) { if(location._id === id) { this.display.push(location); }

试图找到两个数组的交集,为什么我得到的是
TS2339:类型“void”上不存在属性“collection”

所有数组都在同一个类中声明

this.locations.forEach(function(location) {
    this.collection.locations.forEach(function(id) {
        if(location._id === id) {
            this.display.push(location);
        }
    });
});

使用
函数
从调用者那里获取
这个
(在您的情况下,
forEach
中的内容);使用
=>
从外部作用域获取
。因此,使用:

this.locations.forEach(location => {
    this.collection.locations.forEach(id => {
        if(location._id === id) {
            this.display.push(location);
        }
    });
});
我推荐以下阅读材料:


因为您没有使用箭头函数:
this.locations.forEach(location=>{…})。当然,另一个也一样。