简体   繁体   中英

JS - Is it possible to check if a variable is an object?

I'm trying to check if a variable is an object like so:

if(obj && typeof obj === Object) {
    console.log('obj is an object and does not return null value');
}

what am i missing?

typeof returns a string representation of the type, but if you want to check for null then

if(typeof obj === 'object' && obj !== null) {
    console.log('obj is an object and does not return null value');
}

您的代码很好,只需将Object替换为“ object”字符串即可:)

It should be;

typeof obj === 'object'

The typeof operator uses strings as identifiers. You can read more about it on MDN .

'[object Object]' == Object.prototype.toString.call(obj)

the best way to do it is using instanceOf , best practice

if(obj instanceof Object) {
    console.log('obj is an object and does not return null value');
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM