2016-10-02 42 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。