Javascript getTime()返回的时间与时间对象本身不同



Javascript getTime((返回的时间与时间对象本身不同。

function doTime(){
var data = [];
var newDate = new Date('2020-01-01');
for (var i = 0; i < 10; i++) {
newDate.setTime(newDate.getTime() + (1000 * 60 * 60));
console.log(newDate);                //<<----these times are not the same for some reason, why?
data.push({'date': newDate});        //<<----these times are not the same for some reason, why?
}
console.log(data);
}

还有输出!!

Wed Jan 01 2020 03:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 04:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 05:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 06:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 07:00:00 GMT+0200 (Eastern European Standard Time)
................
(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
1: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
2: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
3: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
4: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
................

顺便说一句,我已经用一个稍微不同的代码解决了这个问题,但有人能解释一下为什么会发生这种情况吗?

您没有在循环中创建新的引用,所以每次都会更改相同的newDate。您也在调用console.log,所以在那个时候,它被转换为控制台格式。

最新更新