我有代码
var someObject = ObjectCreator(); //function that is out of my control
someObject
包含一个字段startDate
,它是一个Date对象。
我想复制对象,以便日期在一个星期后在每个对象中。然后应将每个副本放入一个数组中。所以我有......
var someArray = [];
var startDate = someObject.startdate;
for (i=1; i<4; i++) {
var newobject = someObject;
newobject.startdate.setDate(startDate.getDate() + (i*7));
someArray.push(newobject);
}
我注意到startDate
在循环中增加了。我希望它保持不变。我做错了什么?
答案 0 :(得分:3)
因setDate()
更改startdate
。这应该有效:
var todaysDate = new Date();
var someArray = [];
for (i=1; i<4; i++) {
var newobject = {
name: "jim",
startdate: new Date(),
}
newobject.startdate.setDate(todaysDate.getDate() + (i*7));
someArray.push(newobject);
}