Javascript:添加到关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8328508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:35:14  来源:igfitidea点击:

Javascript: Adding to an associative array

javascriptarraysassociative-array

提问by ritch

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

我有一个名为 insert 的函数,它带有两个参数(名称、电话号码)。

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
}

回答by jabclab

Something like this should do the trick:

像这样的事情应该可以解决问题:

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

回答by Stefan

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

我认为您不应该尝试将电话号码解析为整数,因为它可能包含空格、加号 (+),甚至可能以零 (0) 开头。

回答by Tomalak

var users = [];

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

回答by shredder

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

如果需要,可以将函数添加到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"}
]

回答by zzzzBov

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

我将假设您正在使用一些数组引用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");

回答by ioseb

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

JS 中没有“关联数组”这样的术语,但您可以使用以下内容:

var list = [];

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