简体   繁体   中英

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? I think date1 should remain the current date and date2 six months later ...

Thanks

Dates are objects in JavaScript. When you set date2=date1 , both date1 and date2 will reference the same object. 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的引用,而不是值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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