Adding items to a javascript array

+3 votes
asked Dec 13, 2012 in java script by codeg (2,600 points)


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={};

1 Answer

0 votes
answered Dec 13, 2012 by sahana (2,250 points)

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.