簡體   English   中英

JS-是否可以檢查變量是否為對象?

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

它應該是;

typeof obj === 'object'

typeof運算符使用字符串作為標識符。 您可以在MDN上閱讀有關它的更多信息。

'[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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM