Javascript 将元素添加到数组关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8562583/
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
Add element to array associative arrays
提问by Dennis G
Allexamplesof 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 elementto an existing array?
两个问题:如何从头开始生成这个关联数组(是...对象)的数组?如何向现有数组添加新元素?
Thanks for helping me understand javascript.
感谢您帮助我理解 javascript。
回答by James Montagne
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...});
。
回答by SLaks
This is an array of objects.
这是一个对象数组。
You can put more objects in it by calling test.push({ ... })
您可以通过调用将更多对象放入其中 test.push({ ... })
回答by Diode
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 testequal to
使测试等于
[{label:"name1", value:"data1"},
{label:"name2", value:"data2"},
{label:"name3", value:"data3"},
{label:"name4", value:"data4"},
{label:"name5", value:"data5"}]
回答by Rob W
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);