[英]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”字符串即可:)
'[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.