私は別々のtask()オブジェクトに異なる日付を割り当てようとしています。この場合、javascriptは予期せぬ動作をします(下のスニペットの添付出力からわかるように)。JavaScript - setDateは、あらかじめ割り当てられた変数の値をオーバーライドします。
期待される値(期待される出力)は、意図された値(割り当てられているもの)を返していますが、それらを見ている間(実際の出力)、何らかの形ですべての日付変数の値を上書きし、それらのすべて。
どうすればこのようなことが起こるのかご理解ください。
var task = function() {
this.name, this.date,this.id;
this.saveTask = function(n,d)
{
this.name = n;
this.date = d;
};
this.gettask = function()
{
\t return this.id+": "+this.date;
};
}
var d = new Date();
var obj = [];
console.log("Expected Output");
for(i=0;i<5;i++){
\t 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++){
\t console.log(obj[i].gettask());
}
あなたは、各task
に同じ日付オブジェクトを代入している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)
同意します!しかし、毎回異なる日付を 'task.date'に割り当てています。 – Sachink
あなたはそうではありません。 'var d = new Date();'は* d *に日付を割り当てます。 'obj [i] .date = d'は**参照**を日付に割り当てますが、それはコピーされません。 ;-) – RobG
ありがとう!わかった! – Sachink