【问题标题】:typescript 1+1 = 11 not 2打字稿 1+1 = 11 而不是 2
【发布时间】:2018-07-23 16:08:44
【问题描述】:

我有一个 TypeScript 类,顶部没有任何 import 语句。当我 new calculateDate() 并执行 addMonth(new Date(), 1) 时,它向今天添加了 11 个月而不是 2。 m 变量始终是字符串连接的结果,而不是数学加法运算的结果。我什至用两个操作数的字符串形式尝试了 parseInt(),它仍然执行字符串连接。请帮忙。谢谢。

export class calculateDate {

  addMonth(thisDate:Date, monthCount:number){
    if (thisDate && monthCount && monthCount != -1) {
      let m : number = thisDate.getMonth() + monthCount;

      console.log('m=', m);
      let newDate: Date = new Date(thisDate.setMonth(m));

      return newDate;
    }
    else
      return null;
  }
}

【问题讨论】:

  • 使用m = parseInt(month) + parseInt(thisDate.getMonth());
  • 编辑抱怨 parseInt() 中的数字不能是数字..
  • 听起来很奇怪。如果 thisDate 是 Date 那么 getMonth() 是一个 int - 如果 monthCount 是一个数字那么它也是一个 int (或浮点数)
  • 确实不需要强制转换任何一个,但试试+monthCount + thisDate.getMonth()
  • console.log("date",thisDate);console.log("count",monthCount,typeof monthCount);console.log("m",m);

标签: javascript typescript


【解决方案1】:

您将两个字符串相加,尝试将它们解析为 int 或使用此语法 +thisDate.getMonth() + (+monthCount)

【讨论】:

猜你喜欢
  • 2021-08-17
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 2013-01-09
  • 2021-06-27
相关资源
最近更新 更多