【问题标题】:How to pass a value if its null ,if its not null then .toDate() it如果它为空,如何传递一个值,如果它不为空,那么 .toDate() 它
【发布时间】:2021-01-05 18:04:56
【问题描述】:

我正在尝试将日期值传递到 fullCalendar 的 rrule 插件中,如下所示

Endate = null;

rrule: {
        freq: "Daily",
        interval: 1,
        dtstart: StartDate.toDate(),
        until: EndDate.toDate()
                        
        }

在我的 EndDate 中,您可以看到我将其格式化为 .toDate()。

但现在我的 EndDate 也可以是 null,所以当我将它传递给格式化为 .toDate() 时会失败

我的问题是,如果我的 endDate 为 null,我如何才能将该值作为 null 传入,如果我有一个值,那么我可以 .toDate() 它

我试过这样的

until: EndDate == ?? || EndDate.toDate() // 所以如果它的 null 传递那个值,或者如果它不是 null 就传递这个值

但是上面的不起作用。

我试过了

until:EndDate === null ? null:EndDate.toDate() // this works but is there a cleaner way to do it instead of reassigning endDate to null?

【问题讨论】:

  • 不,除了你必须工作之外,没有比这更干净的方法了。
  • @Russ 好吧,我只是觉得它看起来有点乱
  • EndDate ? EndDate.toDate() : null怎么样
  • 你期待什么样的魔法?

标签: javascript typescript fullcalendar-4


【解决方案1】:

我认为Optional Chaining 是您要找的。​​p>

endDate?.toDate() 将尝试调用 toDate 方法,如果 endDate 为 null,则返回 undefined。

如果您需要 until 为 null 而不是未定义,则可以改用 endDate?.toDate() ?? null

【讨论】:

    【解决方案2】:

    您可以使用可选的链接运算符EndDate?.toDate()

    https://codepen.io/niklhs/pen/oNzdaGw?editors=1111

    如果EndDateundefinednull,它不会抛出错误。 相反,它将返回undefined

    【讨论】:

      猜你喜欢
      • 2017-12-28
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 2016-06-24
      • 2019-02-14
      相关资源
      最近更新 更多