如何传递一个值,如果它是 null ,如果它不是 null 那么 .toDate() 它

问题描述

我正在尝试将日期值传递到 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?

解决方法

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

endDate?.toDate() 将尝试调用 toDate 方法并在 endDate 为 null 时返回 undefined。

如果您需要 until 为 null 而不是 undefined,您可以使用 endDate?.toDate() ?? null 代替

,

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

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

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