简体   繁体   English

将元素添加到数组关联数组

[英]Add element to array associative arrays

All examples of adding new elements to associative arrays are going the "easy" way and just have a one dimensional array - my problem of understanding is having arrays within arrays (or is it objects in arrays?). 将新元素添加到关联数组的所有 示例都是“简单”的方式并且只有一维数组 - 我的理解问题是在数组中有数组(或者是数组中的对象?)。

I have the following array: 我有以下数组:

var test = [
            {
                value: "FirstVal",
                label: "My Label 1"
            },
            {
                value: "SecondVal",
                label: "My Label 2"
            }
           ];

Two questions: How to generate this array of associative arrays (yes... object) from scratch ? 两个问题:如何从头开始生成这个关联数组(是...对象)? How to add a new element to an existing array? 如何将新元素添加到现有数组?

Thanks for helping me understand javascript. 谢谢你帮我理解javascript。

I'm not exactly sure what you mean by "from scratch", but this would work: 我不确定你的意思是“从头开始”,但这可行:

var test = [];  // new array

test.push({
                value: "FirstVal",
                label: "My Label 1"
            });  // add a new object

test.push({
                value: "SecondVal",
                label: "My Label 2"
            });  // add a new object

Though the syntax you posted is a perfectly valid way of creating it "from scratch". 虽然您发布的语法是一种非常有效的“从头开始”创建它的方法。

And adding a new element would work the same way test.push({..something...}); 添加一个新元素将以相同的方式运行test.push({..something...}); .

This is an array of objects. 这是一个对象数组。

You can put more objects in it by calling test.push({ ... }) 您可以通过调用test.push({ ... })将更多对象放入其中

var items = [{name:"name1", data:"data1"}, 
             {name:"name2", data:"data2"}, 
             {name:"name3", data:"data3"}, 
             {name:"name4", data:"data4"}, 
             {name:"name5", data:"data5"}]

var test = [];

for(var i = 0; i < items.length; i++){
    var item = {};
    item.label = items[i].name;
    item.value = items[i].data;
    test.push(item);
}

makes test equal to 使测试等于

[{label:"name1", value:"data1"}, 
 {label:"name2", value:"data2"}, 
 {label:"name3", value:"data3"}, 
 {label:"name4", value:"data4"}, 
 {label:"name5", value:"data5"}]

From scratch, the following lines will create an populate an array with objects, using the Array.prototype.push method: 从头开始,以下行将使用Array.prototype.push方法创建一个包含对象的数组:

var test = [];          // Create an array
var obj = {};           // Create an object
obj.value = "FirstVal"; // Add values, etc.
test.push(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM