Javascript: Adding to an associative array

浪子不回头ぞ 提交于 2019-12-21 03:46:26

问题


I have a function called insert which takes two parameters (name, 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
}

回答1:


Something like this should do the trick:

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



回答2:


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




回答3:


var users = [];

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



回答4:


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"}
]



回答5:


I will assume you're using some array reference with insert:

var arr;
function insert(na, nu) {
  nu = Number(nu) || 0;
  //alternatively
  nu = parseInt(nu, 10);
  arr.push({ name: na, number: nu });
}
arr = [];


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



回答6:


There is no such term as an "associative array" in JS, though you can use following:

var list = [];

function insert(name, number) {
  list.push({
    name: name,
    number: number
  });
}


来源:https://stackoverflow.com/questions/8328508/javascript-adding-to-an-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!