JavaScript - 当if语句为true时,代码不会执行?

Jac*_*ith 5 javascript if-statement

所以我为用户提供了3个不同的输入 - 日/月/年,我正在尝试运行if语句来检查月份是1月/ 2月(1还是2),然后是否从年份中减去1 .我的if语句是:

if (month == 1 || month == 2) {
    if (month == 1) {
        year = Number(year) - 1;
    }
    else if (month == 2) {
        year = Number(year) - 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我第一次尝试使用javascript,这非常令人沮丧!你可以看到我的代码在我有月份= 3时运行,但是一旦我将其更改为1或2它就不再执行... 在此输入图像描述

epa*_*llo 4

它失败了,因为您将年份转换为字符串,然后对数字使用字符串操作。控制台中的错误应该清楚地说明这一点。

year = Number(year) - 1
...
var century = year.substring(0,2)
Run Code Online (Sandbox Code Playgroud)

因此,如果要对其执行字符串操作,则需要将数字转换回字符串。

所以要么你做

year = (Number(year) - 1).toString()
Run Code Online (Sandbox Code Playgroud)

或者

var century = year.toString().substring(0,2)
Run Code Online (Sandbox Code Playgroud)

最后,错误“Uncaught TypeError:year.substring is not a function”应该出现在你的开发者控制台中。