NickyTheWrench
NickyTheWrench

Reputation: 3230

Basic forEach not working with Angular/Typescript

I'm trying to rewrite my mobile apps using the latest Angular 6/Ionic 4. I just can't seem to get a basic forEach working. I'm trying all types of ways, but Sublime Text & Angular CLI throws errors. Please see the screenshot below. You can see the red squiggly lines in the Sublime Text Editor. The error is commented above each code block. Does anyone have any idea where I'm going wrong?

Screenshot of forEach Errors

Thanks for your time - please don't hesitate to let me know if you need additional info.

array = [1, 2, 3];

  // Duplicate identifier 'array'. -- Parameter declaration expected.
  array.forEach(function(element) {
    console.log(element);
  })

  // Unexpected token. A constructor, method, accessor, or property was expected.
  this.array.forEach((key : any, val: any) => {
    console.log(val);
  })

  // Cannot find name 'array'. Did you mean 'Array'?
  array.forEach((key : any, val: any) => {
    console.log(val);
  })

  // Cannot find name 'array'. Did you mean 'Array'?
  for (let number of array) {
   console.log(number);
  }

Upvotes: 0

Views: 3489

Answers (2)

alokstar
alokstar

Reputation: 499

You need to be inside methods to access component variables. Try your code in some methods or in constructor. Something like: constructor() { Your code }

Its not required that you should call it in constructor only, you can call the component variables through any methods by using this.componentVaribale inside a method. Obviously you can create local variables in methods using 'let' keyword!

Upvotes: 3

Sunil
Sunil

Reputation: 11243

Issue

You have issue with variable declaration scoping.

Fix

Change 1 : Local variable

let array = [1,2,3]

Change 2 : Accessing instance variable by this.

If you want to access this you must use inside the function.

function test(){
   this.array.forEach(function(){});
}

Upvotes: 0

Related Questions