简体   繁体   English

将项目添加到javascript数组

[英]Adding items to a javascript array

I'm attempting to assign items to an array on a users action, so for example, user clicks "Add", this will add the selected id into the relevant section of the array. 我试图在用户操作中将项目分配给数组,例如,用户单击“添加”,这会将选定的ID添加到数组的相关部分。

The array won't be created at first so I set up an empty array: 首先不会创建该数组,因此我设置了一个空数组:

var Options={};

On the users click, I then want to assign a key to match the option selected from a drop down so I can use this as a reference later on. 在用户单击时,我然后要分配一个键以匹配从下拉菜单中选择的选项,以便以后用作参考。

Eg When the user clicks plus on a record, the option selected from a drop-down is 2. The id of the record they selected is say 5. 例如,当用户单击记录上的加号时,从下拉列表中选择的选项为2。他们选择的记录的ID为5。

I'd like to structure my array like the following:- 我想像下面这样构造我的数组:

[key eg drop down option] => 'records' => array [record_id] [键,例如下拉选项] =>'records'=>数组[record_id]

Each time the user clicks plus next to a record, the id is appended to the correct array based on the drop down selected option. 每次用户单击记录旁边的加号,ID都会根据下拉选择的选项附加到正确的数组中。

[option 1] => 'publication_date' = 12/09/2010, 'records' => [1, 2, 4]
[option 2] => 'publication_date' = 15/09/2010, 'records => [1, 3, 5]

etc, each option from the select box has a publication date and a series of records the user can assign to it. 等等,选择框中的每个选项都有发布日期和用户可以分配给它的一系列记录。

You can do something like this: 您可以执行以下操作:

function AddItem(key, value)  {
   if(Options[key]) Options[key].push(value);
   else Options[key] = [value];
}

For example doing this: 例如这样做:

​AddItem(2, 5);
AddItem(2, 6);

Would result in Options being: 将导致Options为:

{ 2: [5, 6] }

You can give it a try/play with it here . 您可以在此处尝试/试用

An object in javascript is good to store a one key dataset not various keys. javascript中的对象最好存储一个密钥数据集,而不是各种密钥。

ie: var records = {'12/09/2010':[1, 2, 4], '15/09/2010':[1, 3, 5]} 即: var records = {'12/09/2010':[1, 2, 4], '15/09/2010':[1, 3, 5]}

To get the records for the 15/09: records['15/09/2010'] 获取15/09的记录: records['15/09/2010']
Add a new record for a date: records['15/09/2010'].push(6) 为日期添加新记录: records['15/09/2010'].push(6)

If the date change, you need to do something like: 如果日期更改,则需要执行以下操作:
records['17/09/2010'] = records['15/09/2010']; delete records['15/09/2010']

The user is not able to change both at the same time(date and add) and you should do both update actions separately. 用户不能同时更改两个日期和添加,因此您应该分别执行两个更新操作。


Now if you plan to have more keys, you should use an array of objects: 现在,如果您打算拥有更多键,则应该使用对象数组:

var records = [
  {publication_date:'12/09/2010', records:[1, 2, 4], ..., otherProp='...'},
  ...
];

And for each change, loop on the array, find the relevant item and change it. 对于每次更改,在数组上循环,找到相关项目并进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM