[英]JS - Is it possible to check if a variable is an object?
我正在嘗試檢查變量是否是像這樣的對象:
if(obj && typeof obj === Object) {
console.log('obj is an object and does not return null value');
}
我想念什么?
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)
最好的方法是使用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.