JavaScript: Adding to an associative array

I would use something like this;

var contacts = [];
var addContact = function(name, phone) {
    contacts.push({ name: name, phone: phone });
};

// Usage
addContact('John', '999');
addContact('Adam', '5433');

I don’t think you should try to parse the phone number as an integer as it could contain white-spaces, plus signs (+) and maybe even start with a zero (0).


var users = [];

users.push({name: "John", number: "999"});
users.push({name: "Adam", number: "5433"});

Something like this should do the trick:

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

If you want you can add your function to Array.prototype.

Array.prototype.insert = function( key, val ) {
    var obj = {};
    obj[ key ] = val;
    this.push( obj );
    return this;
};

And use it like this.

var my_array = [].insert("John", "999")
                 .insert("Adam", "5433")
                 .insert("yowza", "1");

[
   0: {"John":"999"},
   1: {"Adam":"5433"},
   2: {"yowza":"1"}
]