2017-05-10 14 views
2

我建議改變這一點:使用Javascript - 類型檢查的正確方法

if (typeof user.account.products !== 'undefined') {} 

這樣:

if (user.account && user.account.hasOwnProperty('products')) 

在第二個例子中user.account加入作爲防禦的額外措施,並它是有效的。現在另一部分讓我好奇。

我明白它的作用,但仍然無法包裹我的頭哪一個使用。

+0

的第二個例子給出了另一個檢查層,這是很好的。如果'user.account'不存在,你的第一個例子會拋出一個錯誤。 – wostex

+0

很高興那個其他的答案被刪除了,因爲它是關閉的。因爲它有票據很有用,只是想澄清'(typeof a === undefined)'會告訴你'typeof'的結果是'undefined',這將是一個主要問題。 'typeof' IS'(typeof a ==='undefined')'的正確比較。現在,請參閱下面的問題來回答哪個更好。 – gotmikhail

回答

1

當一個屬性不存在並且您嘗試獲取其類型或值時,您將獲得undefined。如果轉換undefined爲布爾(這是因爲提供的條件表達式的if/then聲明做什麼),你會得到false因爲某些值truthy和其他人falsey

因此,這是測試的不undefined明確的方式:

if (typeof user.account.products !== 'undefined') {} 

而且,這是做同樣的事情的一種含蓄的方式:

if (user.account.products) 

現在您的線路:

if (user.account && user.account.hasOwnProperty('products')) 

比其中任何一個更具體,因爲它不僅測試以查看是否user.account存在,但它也測試以查看該對象是否具有其自己的products屬性。如果這是您打算使用的財產,並且有可能不存在或它可能(但可能不具有products作爲財產),那麼這是測試它的最佳方法。

但是,還有其他方法可以做這種測試。這:

if(account in user && products in user.account) 

檢查各自的屬性是否存在於它們的主機對象中,而不管屬性是否被繼承。

可是,到了最後,如果你關心products財產,你真正需要的是:

if(products in user.account); 

如果products是不是有這個測試將失敗或將其user.account無效。

這一切都取決於你想測試的粒度。

+0

如果使用'hasOwnProperty'進行檢查,如果'產品'存在於原型中,而不是對象本身中,它不會報告'false'? – evolutionxbox

+0

@evolutionxbox是的,它會。但正如我在答覆中所說的那樣,*「它也會測試以查看該對象是否擁有自己的**產品屬性。」* –

+0

當然。 (PS,我的評論是一個問題,而不是挑戰) – evolutionxbox

0

如果我得到你的問題正確,你會問,爲什麼使用:代替

user.account.hasOwnProperty('products') 

user.account.products !== undefined 

在這種情況下,這兩個選項都有效。用這種說法,新選項(hasOwnProperty)更優雅 - 不是假設屬性存在,而是檢查它是否已定義,而是詢問對象是否具有此屬性。

2

第一次檢查是指

if (typeof user.account.products !== 'undefined') { 
    // i will execute if products property is defined on user.account 
    // even is null or 0 
} 

第二檢查裝置(簡體)

if (user.account.hasOwnProperty('products')) { 
    // i will execute if user.account has a property of "products" even if products property is undefined/null/0 
    // and also i wont be executed if user.account is inherited from something has its own 
    // "products" property but not defined on user.account's prototype (inherited property). 

} 

還有,你有沒有提到第三個選擇是這樣的

if ('products' in user.account) { 
    // i will execute if user.account has a property of 
    // "products" even if products property is undefined/null/0 
} 
+0

我喜歡第三種選擇 –

相關問題