简体   繁体   English

javascript setMonth()-将一个月设置为从date1开始的date2。 为什么date1也更改?

[英]javascript setMonth() - setting a month to date2 from date1. Why also date1 change?

I know, title isn't probably clear, but I have this code: 我知道标题可能不清楚,但是我有以下代码:

 var date1=new Date(); alert(date1); var date2=date1; alert(date2); date2.setMonth(date1.getMonth() + 6); alert(date1+" - "+date2); 

Why date1 change? 为什么date1更改? I think date1 should remain the current date and date2 six months later ... 我认为date1应该保留六个月后的当前日期和date2 ...

Thanks 谢谢

Dates are objects in JavaScript. 日期是JavaScript中的对象。 When you set date2=date1 , both date1 and date2 will reference the same object. 当设置date2=date1date1date2都将引用同一对象。 Since they are both references to the same date object, the object may be updated or inspected using either. 由于它们都是对同一日期对象的引用,因此可以使用任一对象来更新或检查对象。

Both the variables are pointing to same date object. 这两个变量都指向相同的日期对象。 You can do this instead 你可以这样做

var date1=new Date();
alert(date1);
var date2=new Date(date1.valueOf());
alert(date2);
date2.setMonth(date1.getMonth() + 6);
alert(date1+" - "+date2);

In this approach, I am creating new object using values of existing one. 通过这种方法,我将使用现有对象的值创建新对象。 Now there are two objects being point by different variables. 现在有两个对象由不同的变量指向。

While you had assigned same object to both variables. 当您将相同的对象分配给两个变量时。

因为date2获取对date1的引用,而不是值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM