javascript – 如何使用包含数组名称的变量将对象文字添加到数组中

我在将新对象文字添加到数组中时遇到问题.当我使用数组名称时,一切正常.但是,当我切换代码以使用保存数组名称的变量时,它不起作用.

我有以下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( { ... }) 
点赞