0

I will try to explain my problem. I have an array of a particular object and, from this array, I want to create a new one with the value of a particular field of each object.

In order to achieve this, I tried to use array.forEach() method but I get a variable undefined error inside the forEach() function. This is my code:

var values: number[];
measures.forEach((measure)=>{
    values.push(measure.value);
});

I've tried to declare the array values as public (and access this.values) and also to declare it in the function where I make the forEach and neither way worked.

Here is the error I get in the browser (angular CLI reports no problem):

ERROR TypeError: "values is undefined"
2
  • 3
    You must initialize the array: let values: number[] = [];. Commented Apr 3, 2019 at 19:27
  • 1
    You need to initialize the values array, not just define. Try values: number[] = []; instead. Commented Apr 3, 2019 at 19:27

1 Answer 1

2

Try to initialize your array rather than just declare it as

values: number[] = [];

You do not need the var keyword in angular if you are declaring a variable directly inside a component class. If you need to do it inside a function, use let keyword. more information HERE

Sign up to request clarification or add additional context in comments.

2 Comments

I do need the var keyword If I create my array inside a function.
then use let, not var @nlopez

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.