简体   繁体   English

如何在Javascript中将每个元素数组推入2个属性?

[英]How do I push to a 2-attribute per element array in Javascript?

Let's say I want to achieve the following array structure but programmatically by using the push() function in js: 假设我想通过使用js中的push()函数以编程方式实现以下数组结构:

var arr = [
{id: 1, txt: "First Element"},
{id: 2, txt: "Second Element"},
{id: 3, txt: "Third Element"}
];

My idea is something of the following format: 我的想法是采用以下格式:

var arr = [];
var id = 1;
var text = "First Element";

for (var i=0;i<3;i++){
arr.push({id,text});
}

This is wrong because I'm not passing the column names anywhere. 这是错误的,因为我没有在任何地方传递列名。 How do I go about this? 我该怎么办?

Thanks 谢谢

You were almost there, you just need to specify both the property name and the value, like this: 您就快到了,只需指定属性名称和值,如下所示:

 var arr = []; for (var i = 0; i < 3; i++) { arr.push({ id : i+1, txt : "Element " + (i+1) }); } console.log(arr); 

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

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