我无法将新的对象文字放入数组中。当我使用数组名称时,一切正常。但是,当我切换代码以使用包含数组名称的变量时,它不起作用。
我有 6 个数组,如下所示,它们列在我的页面上。单击会将单击的数组的名称保存到名为 whichList 的变量中。
以下是其中的三个数组:
student0 = [
{
status: "completed",
goal: "go to store",
duedate: "November 1",
datecreated: ""
}, {
status: "completed",
goal: "buy beer",
duedate: "November 2",
datecreated: ""
}
];
student1 = [
{
status: "completed",
goal: "go to the beach",
duedate: "November 7"
}, {
status: "completed",
goal: "swim without drowning",
duedate: "November 8",
datecreated: ""
}
];
student2 = [
{
status: "completed",
goal: "fly a plane",
duedate: "November 11",
datecreated: ""
}, {
status: "completed",
goal: "don't crash",
duedate: "November 12",
datecreated: ""
}
];
这是工作代码,它直接指定数组名称。单击后,它会在控制台中显示我更新的数组:
$('#savegoal').click(function() {
datecreated = new Date();
student0[student0.length] = {
status: "pending",
goal: "\"" + $('#thegoal').val() + "\"",
duedate: "\"" + $('#thedeadline').val() + "\"",
datecreated: "\"" + datecreated + "\""
};
return console.log(student0);
});
这是非工作代码。我想使用 whichList 变量。
我使用了 console.log 来检查变量在函数开头是否显示了正确的数组名称。那里一切都好。但是我在控制台中得到的只是数组变量,而不是我在工作版本中所做的数组的内容。
$('#savegoal').click(function() {
datecreated = new Date();
whichList[whichList.length] = {
status: "pending",
goal: "\"" + $('#thegoal').val() + "\"",
duedate: "\"" + $('#thedeadline').val() + "\"",
datecreated: "\"" + datecreated + "\""
};
return console.log(whichList);
});