首页 > 解决方案 > Moment js 不适用于 1 月(第 0 个月)

问题描述

我知道现在月份的索引为 0。基本上我将 this.month 设置为 0 到 11 之间的任何整数并运行以下代码。出于某种原因,它不想更新一月的时刻变量(编号为 0)。出了什么问题,我该如何解决?

const d: Moment = moment();
if (this.month) d.month(this.month);
console.log("Month value: " + this.month);
console.log("Moment value: " + d.month());

Console.log 为 this.month = 2(三月)返回以下内容

月值:2 矩值:2

Console.log 为 this.month = 1(二月)返回以下内容

月值:1 时刻值:1

Console.log 为 this.month = 0(一月)返回以下内容

月值:0 矩值:1

标签: javascriptmomentjs

解决方案


if (this.month)

this.month如果是假值(如 0),则以下指令将不会运行。

正如 HMR 建议的那样,您可能希望使用===运算符(或其否定!==)来检查this.monthis not nullnor undefined


推荐阅读