I'm trying to assign different dates to separate task() objects; but javascript is behaving unexpectedly in this case, as can be seen from attached output for below snippet.
While assigning dates(i.e. Expected Output) it's returning intended values(same that are being assigned), but while viewing them(i.e. Actual Output), it somehow overrides value for all date variables and returns only the last assigned value for all of them.
Please help me understand how is this happening!
var task = function() {
this.name, this.date,this.id;
this.saveTask = function(n,d)
{
this.name = n;
this.date = d;
};
this.gettask = function()
{
return this.id+": "+this.date;
};
}
var d = new Date();
var obj = [];
console.log("Expected Output");
for(i=0;i<5;i++){
obj[i] = new task();
obj[i].id = i;
d.setDate(i);
obj[i].date = d;
console.log(i+": "+d); //Display assinged value
}
console.log("Actual Output");
for(i=0;i<5;i++){
console.log(obj[i].gettask());
}
OUTPUT IN CONSOLE
Expected Output
0: Sat Apr 30 2016 10:42:20 GMT+0530 (India Standard Time)
1: Fri Apr 01 2016 10:42:20 GMT+0530 (India Standard Time)
2: Sat Apr 02 2016 10:42:20 GMT+0530 (India Standard Time)
3: Sun Apr 03 2016 10:42:20 GMT+0530 (India Standard Time)
4: Mon Apr 04 2016 10:42:20 GMT+0530 (India Standard Time)
Actual Output
0: Mon Apr 04 2016 10:42:20 GMT+0530 (India Standard Time)
1: Mon Apr 04 2016 10:42:20 GMT+0530 (India Standard Time)
2: Mon Apr 04 2016 10:42:20 GMT+0530 (India Standard Time)
3: Mon Apr 04 2016 10:42:20 GMT+0530 (India Standard Time)
4: Mon Apr 04 2016 10:42:20 GMT+0530 (India Standard Time)
You're assigning the same date object to each task
. Create a new date for each one in the loop.
for (let i = 0; i < 5; i++) {
let d = new Date();
d.setDate(i);
let t = new task();
t.date = d;
// etc
obj.push(t);
}
I suggest you have a read of this ~ Is JavaScript a pass-by-reference or pass-by-value language?
Note that the time portion of each date object may be different due to execution time. If you want them all to have the same time but different dates, you'll need to make a slight change.