简体   繁体   English

JS-是否可以检查变量是否为对象?

[英]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 typeof返回该类型的字符串表示形式,但是如果要检查null,则

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. typeof运算符使用字符串作为标识符。 You can read more about it on MDN . 您可以在MDN上阅读有关它的更多信息。

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

the best way to do it is using instanceOf , best practice 最好的方法是使用instanceOf最佳实践

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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