Javascript Typescript如何访问foreach循环中的组件变量?

Javascript Typescript如何访问foreach循环中的组件变量?,javascript,angular,typescript,Javascript,Angular,Typescript,有人能告诉我如何在foreach循环中访问组件变量吗? 这是我的 此的值取决于您所在的范围。考虑这样做: public testVariable:number; test(){ console.log('fired'); var x =[1,2,3,4]; var self = this; x.forEach(function (e){ self.testVariable = e; }) console.log( this

有人能告诉我如何在foreach循环中访问组件变量吗? 这是我的


的值取决于您所在的范围。考虑这样做:

public testVariable:number;

test(){
    console.log('fired');
    var x  =[1,2,3,4];

    var self = this;
    x.forEach(function (e){
        self.testVariable = e;
    })

    console.log( this.testVariable);
}
如果使用
函数(e)
,则其中的
this
将引用函数的作用域而不是类

使用
箭头功能
(或
胖箭头
):

只有1个参数时,也可以省略其周围的括号:

x.forEach(e => {
    this.testVariable = e;
})

这里有一篇很好的文章解释了它的行为:

这样做的结果不总是
4
?另外,不是所有匿名函数都是“lambda”吗?@evolutionxbox你是对的,lambda是匿名函数的同义词,我更正了答案。谢谢你的提醒,这正是我要找的!es5需要实现可能的副本,但在typescript等中已经过时
x.forEach((e) => {
    this.testVariable = e;
})
x.forEach(e => {
    this.testVariable = e;
})