2016-10-02 62 views
0

的條件我有一個用戶數據庫是這樣的:JS如果未定義

const user = { 
    subscription: { 
    plan: 'free_trial', 
    }, 
}; 

我需要用戶改變計劃之前,要檢查一些條件。

const currentDate = new Date(); 
if (user.subscription.trialExpDate > currentDate) { 
    // do something 
} else { 
    // trialExpDate is either undefined or <= currentDate 
    user.subscription.trialExpDate = currentDate; 
} 

我的問題是,對於某些用戶trialExpDateundefined。可以將undefinedcurrentDate對象進行比較嗎?或者我需要檢查一下是否存在trialExpDate

+1

什麼是'user.subscription.trialExpDate'?它是一個字符串嗎?試試'new Date(user.subscription.trialExpDate)' – Rayon

+0

'user.subscription。trialExpDate'或者是'undefined'或者是'date'對象 – cocacrave

+1

'undefined> new Date();'將永遠是'false' ..我會在比較之前測試這個值.. – Rayon

回答

3

我建議檢查hasownproperty。 樣品:

if (user.subscription.hasOwnProperty('trialExpDate') && user.subscription.trialExpDate > currentDate) { 
    // do something 
} else { 
    // trialExpDate is either undefined or <= currentDate 
    user.subscription.trialExpDate = currentDate; 
} 
+0

謝謝我會這樣做:) – cocacrave

+1

'trialExpDate'不是'userProperty'的'用戶'對象,它屬於'user.subscription' – Rayon

+0

是啊我想了:) – cocacrave

1

你可以只檢查它是否null

if (user.subscription.trialExpDate != null || user.subscription.trialExpDate > currentDate) { 
    // do something 
} 
else { 
    // do something else 
} 

variable != null將同時檢查變量是否爲空或未定義。

+0

哦,我從來不知道這一點。這實際上很酷。謝謝 – cocacrave

+1

你可以在這裏閱讀更多:http://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null –

+0

如果'user.subscription.trialExpDate'爲'0 '?我會有一個功能來測試它是否是一個有效的日期.. .. – Rayon

0

簡而言之:如果你確定user.subscription.trialExpDate不能是null,使用原來的代碼是非常

請參閱how the JavaScript relational comparison operators coerce types

如果user.subscription總是存在的,它始終是一個對象,一個Date對象之間的比較,以及undefinedNaN,被評價爲false。但是,對於null,其評估爲+0,因此null < (new Date)將爲true,null > (new Date)將爲false

當JavaScript的關係比較工作,

  1. Date對象轉換爲其時間戳,這是(The Date object).valueOf()

  2. 原語被轉換爲number,這意味着:

    • 一個undefined被轉換爲NaN;
    • a null轉換爲+0
  3. 然後按照您對操作員的期望在每個項目之間執行比較。請注意,涉及NaN的任何比較評估爲false。