I display 5 datapoints in array, then 5 datapoints in array and finally got a globalArray with this 2 array.
So what I want is:
I am trying to do something but I got an error :
cannot read property 'Average' of undefined.
Expected result: ['up','down'] [null,2019-01-15T08:26:00.000Z]
// ***** SCRIPT CONTINUE
getAllMetrics(regions).then(res => {
console.log(res);
/*
[[{Timestamp: 2019-01-15T08:26:00.000Z, Average: 200},
{Timestamp: 2019-01-15T08:32:00.000Z, Average: 200},
{Timestamp: 2019-01-15T08:26:00.000, Average: 200},
{Timestamp: 2019-01-15T08:29:00.000Z, Average: 200},
{Timestamp: 2019-01-15T08:35:00.000Z, Average: 200}],
[{Timestamp: 2019-01-15T08:26:00.000Z, Average: 400},
{Timestamp: 2019-01-15T08:32:00.000Z, Average: 400},
{Timestamp: 2019-01-15T08:26:00.000, Average: 400},
{Timestamp: 2019-01-15T08:29:00.000Z, Average: 200},
{Timestamp: 2019-01-15T08:35:00.000Z, Average: 200}]] */
tabRES = [];
//Loop regions
var i = -1;
TsTAB = [null, null, null];
var a=-1;
while( tabReg[++a] ){
TsTAB.push( null );
}
while (res[++i]) {
Avg = {
up: 0,
down: 0
};
Ts = "";
RespARRAY = res[i];
var j = -1;
while (RespARRAY[++j]) {
if (RespARRAY[j].Average == 200) {
Avg.up++ // IF 200 -> UP
//and push array TS
} else {
Avg.down++ // -> DOWN
//Retrieve the last
Ts = Ts || RespARRAY[j].Timestamp;
}
}
if (Avg.up > Avg.down) {
tabRES.push('up');
} else {
tabRES.push('down');
TsTAB[i] = TsTAB[i] || Ts;
}
}
console.log(tabRES);
console.log(TsTAB);
}).catch(err => {
console.log(err);
});
The error is caused by while (RespARRAY[++j])
. The loop needs an end condition. Currently, it iterates through your five values and looks for a sixth, which doesn't exist. So RespARRAY[j]
is undefined, and javascript can't find the "average" property of that undefined value.
You could begin the loop with
if(j > 4){ break; }
or, better,
if(j >= RespARRAY.length){ break; }
or you could use a for loop. (See www.w3schools.com/js/js_loop_for.asp )
Note that you'll find this same issue in your outer ( i
) loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.