简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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