0

I have a demo here https://stackblitz.com/edit/angular-w7vavy

I'm trying to create a function that will generate an array of objects that contain random numbers an then output the array on the screen

I just getting an error - Error: Cannot set property '0' of undefined

createData = () => {
    for(let n=0; n<=this.dates.length;n++){
      for(let i= 0; i<=4; i++){
        this.testData[i] = {
          data_1: Math.random() * (this.max - this.min),
          data_2: Math.random() * (this.max - this.min),
          data_3: Math.random() * (this.max - this.min),
          data_4: Math.random() * (this.max - this.min),
          date: this.dates[i]
        }
      }
    }
}

3 Answers 3

2

Initialize this.testData = [] before the loop, use this.testData.push({...the object...}) inside the loop. Maybe this.dates has to be initialized also.

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

Comments

2

You need to explicitly define testData in your code before loop.

this.testData = [];

Comments

1

I think initialization has to be taken care properly. I removed typescript syntax and made it plain JS. Here you go:

testData = []
dates = ['2014', '2015', '2016', '2017']

min = 10;
max = 100;
createData = () => {
    for (let n = 0; n <= dates.length; n++) {
        for (let i = 0; i < 4; i++) {
            testData[i] = {
                data_1: Math.random() * (max - min),
                data_2: Math.random() * (max - min),
                data_3: Math.random() * (max - min),
                data_4: Math.random() * (max - min),
                date: dates[i]
            }
        }
    }
}
createData();
console.log(testData);

Comments

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.