https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth
來看MDN的說明
The current day of month will have an impact on the behavior 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 January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.
這里已經(jīng)說明了,setMonth的時候會把當(dāng)前的date應(yīng)用到目標(biāo)的month, 如果date超出目標(biāo)月份的日期,可能就會到下個月了。舉個例子
當(dāng)前是2023-03-30
如果new Date()? 之后setMonth(date.getMonth() - 1) 也就是上個月,實際上結(jié)果會變成 2023-03-02, 因為set完之后變成2023-02-30, 實際2月28天就到了03-02
let date = new Date();
date.setMonth(date.getMonth() - 1)