Javascript数组取消移位新日期减去1天

时间:2019-06-02 16:29:06

标签: javascript arrays

我从以下代码中得到一些奇怪的结果:

a = [];
a[0] = new Date();
console.log("1 Element Added: "+a.length + " - " + a.toString());

//"1 Element Added: 1 - Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"


a.unshift(new Date(new Date(new Date().setDate(a[0].getDate() - 1))));
console.log("First Unshift: "+a.length + " - " + a.toString());

//"First Unshift: 2 - Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"


a.unshift(new Date(new Date(new Date().setDate(a[0].getDate() - 1))));
console.log("Second Unshift: "+a.length + " - " + a.toString());

//"Second Unshift: 3 - Fri May 31 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"


a.unshift(new Date(new Date(new Date().setDate(a[0].getDate() - 1))));
console.log("Third Unshift: "+a.length + " - " + a.toString());

//"Third Unshift: 4 - Sun Jun 30 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Fri May 31 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"

相同的代码在第一次和第二次都有效,但是第三次​​运行给出了意外的结果-应该是2019年5月30日星期四,而不是2019年6月30日星期四有人可以告诉我我在做什么错吗?

谢谢。

2 个答案:

答案 0 :(得分:2)

最里面的new Date()总是在6月创建一个Date实例。将月份中的日期设置为30时,您将日期强制为6月30日,而不是5月30日。

呼叫.setDate() 可以更改月份,但是仅当月份中的某天没有意义时(较小(零或负)或较大(如33)。由于6月30日确实是真实的一天,所以该月没有变化。

答案 1 :(得分:1)

@Pointy和@Titus已经解释了为什么代码无法按预期工作的原因。在这里,我将您的代码修改为可以根据需要进行响应:

a = [];
a[0] = new Date();
console.log("1 Element Added: "+a.length + " - " + a.toString());

//"1 Element Added: 1 - Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"

a.unshift(new Date(a[0]));
a[0].setDate(a[0].getDate()-1);
console.log("First Unshift: "+a.length + " - " + a.toString());

//"First Unshift: 2 - Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"


a.unshift(new Date(a[0]));
a[0].setDate(a[0].getDate()-1);
console.log("Second Unshift: "+a.length + " - " + a.toString());

//"Second Unshift: 3 - Fri May 31 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"


a.unshift(new Date(a[0]));
a[0].setDate(a[0].getDate()-1);
console.log("Third Unshift: "+a.length + " - " + a.toString());