设置下一个月或上一个月没有实际日期的操作日期不按预期工作
>var date = new Date('2018/10/31');
undefined
>date
Wed Oct 31 2018 00:00:00 GMT-0600 (hora estándar central)
>date.setMonth(date.getMonth() + 1);
1543644000000
>date
Sat Dec 01 2018 00:00:00 GMT-0600 (hora estándar central)
这是一个错误吗?是否应该报告或将其视为预期行为?
这是记录在案的行为。引用自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth例如:
If a parameter you specify is outside of the expected range, setMonth() attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1, and 3 will be used for month.
The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.
在您的例子中,它执行上面第二段中描述的操作:您已将月份更改为 11 月,但没有更改日期。当然,没有 11 月 31 日,因此 JavaScript 会自动将日期设置为下一个有效日期,即 12 月 1 日。