[英]Angular - generate array of objects and display the data
I have a demo here https://stackblitz.com/edit/angular-w7vavy 我在这里有一个演示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 我刚收到一个错误-错误:无法设置未定义的属性“ 0”
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]
}
}
}
}
You need to explicitly define testData in your code before loop. 您需要在循环之前在代码中显式定义testData。
this.testData = []; this.testData = [];
Initialize this.testData = []
before the loop, use this.testData.push({...the object...})
inside the loop. 在循环之前初始化
this.testData = []
,在循环内使用this.testData.push({...the object...})
。 Maybe this.dates
has to be initialized also. 也许
this.dates
也必须初始化。
I think initialization has to be taken care properly. 我认为初始化必须适当注意。 I removed typescript syntax and made it plain JS.
我删除了打字稿语法,并将其制成普通的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.