简体   繁体   中英

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.

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.

I'd like to structure my array like the following:-

[key eg drop down option] => 'records' => array [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.

[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:

{ 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.

ie: 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']
Add a new record for a date: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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