I can't seem to figure out why I can't get the information out of the array
const usedPlatformLog: Date[] = []
users.forEach(el => {
usedPlatformLog.push(el.lastUsed)
})
console.log(usedPlatformLog) // shows array with indexes 0 and 1 (picture attached)
console.log(usedPlatformLog[0]) // log response undefined
CodePudding user response:
undefined
is a valid value, and can be pushed into arrays.
your array is [undefined, undefined]
probably because users[0].lastUsed
and users[1].lastUsed
are also undefined. Maybe console.log(users)
so you can actually see what's in that array.
CodePudding user response:
This may be happening because the lastUsed
property of the el
object is not defined or it is not of type Date
.
In JavaScript, when you try to access a property of an object that is not defined or it is not of the expected type, it will return undefined
.
To fix this issue, you can check if the lastUsed
property exists and if it is of type Date
before pushing it to the usedPlatformLog
array.
Here is an example:
const usedPlatformLog: Date[] = []
users.forEach(el => {
if (el.lastUsed && el.lastUsed instanceof Date) {
usedPlatformLog.push(el.lastUsed)
}
})
console.log(usedPlatformLog) // should now show the correct values in the array
console.log(usedPlatformLog[0]) // should now return the expected value