我在将新对象字面量放入数组时遇到问题。当我使用数组名称时,一切正常。但是,当我将代码切换为使用保存数组名称的变量时,它不起作用。
我有 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);
});
最佳答案
您可以使用 window[whichList]
,因为数组变量可能在全局/窗口范围内:
var whichList = "student0";
var theList = window[whichList];
theList[theList.length] = { ... }; // consider using instead: theList.push( { ... })
关于javascript - 如何使用保存数组名称的变量将对象文字添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414818/