Why inside a foreach loop you can not use global variables in Typescript?

Viewed 4237

I have a property with a simple foreach loop, inside this loop I want to use a global variable but I receive a error.

When I

Create an internal variable of the property that receives the global value to be able to use it within the loop

simpleArray = [0,1,2];
simpleArray2 = [0,1,2];

get resume() {
    let localArray = this.simpleArray;
    this.simpleArray2.forEach(function (element, index) {
        console.log(localArray);         // [0,1,2]
        console.log(this.simpleArray);   // return error undefined
    });
    return 'something';
}
1 Answers

Use arrow function instead :

this.simpleArray2.forEach((element, index) => {
  console.log(localArray); 
  console.log(this.simpleArray); 
});
Related