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

时间:2021-03-29 21:21:15

I'm having trouble getting a new object literal into an array. When I use the array name, everything works. But when I switch the code to use a variable that is holding the array name, it doesn't work.

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

I've got 6 arrays like the following, and they're listed on my page. A click saves the name of the array clicked into a variable called whichList.

我有6个阵列,如下所示,它们列在我的页面上。单击将保存单击的数组名称保存到名为whichList的变量中。

Here are three of the arrays:

以下是三个数组:

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: ""
  }
];

Here's the working code, which is specifying the array name directly. It shows my updated array in the console after the click:

这是工作代码,它直接指定数组名称。单击后,它会在控制台中显示我更新的数组:

$('#savegoal').click(function() {
  datecreated = new Date();
  student0[student0.length] = {
    status: "pending",
    goal: "\"" + $('#thegoal').val() + "\"",
    duedate: "\"" + $('#thedeadline').val() + "\"",
    datecreated: "\"" + datecreated + "\""
  };
  return console.log(student0);
});

Here's the non-working code. I want to use the whichList variable.

这是非工作代码。我想使用whichList变量。

I've used console.log to check that the variable is showing the correct array name at the beginning of the function. All good there. But all I get in the console is the array variable, not the contents of the array as I do in the working version.

我已经使用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);
});

3 个解决方案

#1


3  

You can use window[whichList], since the array variable is presumably in the global/window scope:

您可以使用window [whichList],因为数组变量可能在全局/窗口范围内:

var whichList = "student0";
var theList = window[whichList];
theList[theList.length] = { ... };   // consider using instead: theList.push( { ... }) 

#2


0  

A direct answer to your question :

直接回答您的问题:

var wichList = null;
$('#savegoal').click(function() {
  if (wichList == null){
      alert('No list selected');
  }
  // don't forget the "var", otherwise "datecreated"
  // will actually be a global variable
  var datecreated = new Date();
  // ".push()" adds the given value at the end of the array
  wichList.push({
    status: "pending",
    goal: "\"" + $('#thegoal').val() + "\"",
    duedate: "\"" + $('#thedeadline').val() + "\"",
    datecreated: "\"" + datecreated + "\""
  });
  return console.log(wichList);
});

//somewhere else in your code :
if (somecond) {
    wichList = student0;
} elseif (somecond) {
    wichList = student1;
} else {
    wichList = null;
}

The above code works : in javascript, an array variable is actually a reference to the array's content

上面的代码有效:在javascript中,数组变量实际上是对数组内容的引用

var a = [];
var b = a;
// b an a are now references to the same array,
// any modification to a will be "seen" by b, and vice versa :
a.push(1);
b.push(2);
// a == b == [1,2]

However, given the names of your "student" variables, these lists should probably be stored in an array :

但是,根据您的“学生”变量的名称,这些列表可能应存储在数组中:

var students = [];

students[0] = [{
    status: "completed",
    goal: "go to store",
    duedate: "November 1",
    datecreated: ""
  }, {
    status: "completed",
    goal: "buy beer",
    duedate: "November 2",
    datecreated: ""
  }];

students[1] = [ ...

You can now use the index in this array as a way to identify a student, maybe with an extra select :

您现在可以使用此数组中的索引作为识别学生的方法,可能还有一个额外的选择:

<select id="student">
    <option value="0">student 0</option>
    <option value="1">student 1</option>
    ...
</select>

and use it in your click callback :

并在您的点击回调中使用它:

$('#savegoal').click(function() {
  var datecreated = new Date();
  var i = $('#student').val();
  students[i].push({
    status: "pending",
    goal: "\"" + $('#thegoal').val() + "\"",
    duedate: "\"" + $('#thedeadline').val() + "\"",
    datecreated: "\"" + datecreated + "\""
  });
  return console.log(students[i]);
});

#3


-1  

First, use an array instead of separate variables:

首先,使用数组而不是单独的变量:

var student = [
    [{
        status: "completed",
        goal: "go to store",
        duedate: "November 1",
        datecreated: ""
    }, {
        status: "completed",
        goal: "buy beer",
        duedate: "November 2",
        datecreated: ""
    }],
    [{
        status: "completed",
        goal: "go to the beach",
        duedate: "November 7"
    }, {
        status: "completed",
        goal: "swim without drowning",
        duedate: "November 8",
        datecreated: ""
    }],
    [{
        status: "completed",
        goal: "fly a plane",
        duedate: "November 11",
        datecreated: ""
    }, {
        status: "completed",
        goal: "don't crash",
        duedate: "November 12",
        datecreated: ""
    }],
    ...
];

Then , whichList should be an index into the array (i.e. a number from 0 to 5) rather than the name of a variable, and you can do:

然后,whichList应该是数组的索引(即0到5之间的数字)而不是变量的名称,你可以这样做:

$('#savegoal').click(function() {
    datecreated = new Date().toString();
    student[whichList].push({
        status: "pending",
        goal: $('#thegoal').val(),
        duedate: $('#thedeadline').val(),
        datecreated: datecreated
    });
});

You don't need to concatenate all those "\"" -- quotes are part of the notation when typing string literals, you don't need them what you're getting the strings from variables or expressions.

你不需要连接所有那些“\”“ - 在键入字符串文字时,引号是符号的一部分,你不需要它们从变量或表达式中获取字符串。

Here's how you can do it if you want to use student IDs as the key to finding each student:

如果您想使用学生ID作为查找每个学生的关键,您可以采用以下方法:

var student = {};
student[student0] = [
    {
        status: "completed",
        goal: "go to store",
        duedate: "November 1",
        datecreated: ""
    }, {
        status: "completed",
        goal: "buy beer",
        duedate: "November 2",
        datecreated: ""
    }];
student[student1] = [
    {
        status: "completed",
        goal: "go to the beach",
        duedate: "November 7"
    }, {
        status: "completed",
        goal: "swim without drowning",
        duedate: "November 8",
        datecreated: ""
    }];
student[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();
    push(student[whichStudentId],{
        status: "pending",
        goal: $('#thegoal').val(),
        duedate: $('#thedeadline').val(),
        datecreated: datecreated
    });
    console.log(whichList);
});

#1


3  

You can use window[whichList], since the array variable is presumably in the global/window scope:

您可以使用window [whichList],因为数组变量可能在全局/窗口范围内:

var whichList = "student0";
var theList = window[whichList];
theList[theList.length] = { ... };   // consider using instead: theList.push( { ... }) 

#2


0  

A direct answer to your question :

直接回答您的问题:

var wichList = null;
$('#savegoal').click(function() {
  if (wichList == null){
      alert('No list selected');
  }
  // don't forget the "var", otherwise "datecreated"
  // will actually be a global variable
  var datecreated = new Date();
  // ".push()" adds the given value at the end of the array
  wichList.push({
    status: "pending",
    goal: "\"" + $('#thegoal').val() + "\"",
    duedate: "\"" + $('#thedeadline').val() + "\"",
    datecreated: "\"" + datecreated + "\""
  });
  return console.log(wichList);
});

//somewhere else in your code :
if (somecond) {
    wichList = student0;
} elseif (somecond) {
    wichList = student1;
} else {
    wichList = null;
}

The above code works : in javascript, an array variable is actually a reference to the array's content

上面的代码有效:在javascript中,数组变量实际上是对数组内容的引用

var a = [];
var b = a;
// b an a are now references to the same array,
// any modification to a will be "seen" by b, and vice versa :
a.push(1);
b.push(2);
// a == b == [1,2]

However, given the names of your "student" variables, these lists should probably be stored in an array :

但是,根据您的“学生”变量的名称,这些列表可能应存储在数组中:

var students = [];

students[0] = [{
    status: "completed",
    goal: "go to store",
    duedate: "November 1",
    datecreated: ""
  }, {
    status: "completed",
    goal: "buy beer",
    duedate: "November 2",
    datecreated: ""
  }];

students[1] = [ ...

You can now use the index in this array as a way to identify a student, maybe with an extra select :

您现在可以使用此数组中的索引作为识别学生的方法,可能还有一个额外的选择:

<select id="student">
    <option value="0">student 0</option>
    <option value="1">student 1</option>
    ...
</select>

and use it in your click callback :

并在您的点击回调中使用它:

$('#savegoal').click(function() {
  var datecreated = new Date();
  var i = $('#student').val();
  students[i].push({
    status: "pending",
    goal: "\"" + $('#thegoal').val() + "\"",
    duedate: "\"" + $('#thedeadline').val() + "\"",
    datecreated: "\"" + datecreated + "\""
  });
  return console.log(students[i]);
});

#3


-1  

First, use an array instead of separate variables:

首先,使用数组而不是单独的变量:

var student = [
    [{
        status: "completed",
        goal: "go to store",
        duedate: "November 1",
        datecreated: ""
    }, {
        status: "completed",
        goal: "buy beer",
        duedate: "November 2",
        datecreated: ""
    }],
    [{
        status: "completed",
        goal: "go to the beach",
        duedate: "November 7"
    }, {
        status: "completed",
        goal: "swim without drowning",
        duedate: "November 8",
        datecreated: ""
    }],
    [{
        status: "completed",
        goal: "fly a plane",
        duedate: "November 11",
        datecreated: ""
    }, {
        status: "completed",
        goal: "don't crash",
        duedate: "November 12",
        datecreated: ""
    }],
    ...
];

Then , whichList should be an index into the array (i.e. a number from 0 to 5) rather than the name of a variable, and you can do:

然后,whichList应该是数组的索引(即0到5之间的数字)而不是变量的名称,你可以这样做:

$('#savegoal').click(function() {
    datecreated = new Date().toString();
    student[whichList].push({
        status: "pending",
        goal: $('#thegoal').val(),
        duedate: $('#thedeadline').val(),
        datecreated: datecreated
    });
});

You don't need to concatenate all those "\"" -- quotes are part of the notation when typing string literals, you don't need them what you're getting the strings from variables or expressions.

你不需要连接所有那些“\”“ - 在键入字符串文字时,引号是符号的一部分,你不需要它们从变量或表达式中获取字符串。

Here's how you can do it if you want to use student IDs as the key to finding each student:

如果您想使用学生ID作为查找每个学生的关键,您可以采用以下方法:

var student = {};
student[student0] = [
    {
        status: "completed",
        goal: "go to store",
        duedate: "November 1",
        datecreated: ""
    }, {
        status: "completed",
        goal: "buy beer",
        duedate: "November 2",
        datecreated: ""
    }];
student[student1] = [
    {
        status: "completed",
        goal: "go to the beach",
        duedate: "November 7"
    }, {
        status: "completed",
        goal: "swim without drowning",
        duedate: "November 8",
        datecreated: ""
    }];
student[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();
    push(student[whichStudentId],{
        status: "pending",
        goal: $('#thegoal').val(),
        duedate: $('#thedeadline').val(),
        datecreated: datecreated
    });
    console.log(whichList);
});