JavaScript: Adding to an associative array

ritch picture ritch · Nov 30, 2011 · Viewed 50.7k times · Source

I have a function called insert which takes two parameters (name and telnumber).

When I call this function I want to add to an associative array.

So for example, when I do the following:

insert("John", "999");
insert("Adam", "5433");

I want to it so be stored like this:

[0]
{
name: John, number: 999
}
[1]
{
name: Adam, number: 5433
}

Answer

jabclab picture jabclab · Nov 30, 2011

Something like this should do the trick:

var arr = [];
function insert(name, number) {
    arr.push({
        name: name,
        number: number
    });        
}