typeof(nonexistingobj)
returns 'undefined' BUT
typeof(nonexistingobj.nonexistentproperty)
does not generate 'undefined' as I was expecting, but something called a Reference Error - how do I detect this?
I'm trying to do sub-property detection on the response from an API. (Specifically, the API returns a sub object called data.paging.next
when there's another page of API results to get, but no 'next' sub object if it just returned the last page).
Don't try to access a property of undefined
. Test if the variable you are trying to access is defined first.
if (typeof obj !== "undefined") {
typeof obj.nonexistentproperty;
}
To catch errors you can use try/catch:
try {
console.log(typeof nonexistingobj.nonexistentproperty);
} catch (error) {
console.log('Message error: ' + error.message);
}
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.