简体   繁体   English

根据长度动态创建对象数组

[英]Creating array of objects dynamically based on length

I have the length of my previous object and i need to create a new array of objects based on the length with new key's. 我有我以前的对象的长度,我需要根据带有新键的长度创建一个新的对象数组。

Length = 3;

var newArray = [];
for(var i =0; i <3; i++){
    var Object = {};
    Object['newKey'] = 1;
    newArray.push(Object);
}

This would eventually create newArray of Objects whose length is 3 containing something like this.. newArray[0],[1],[2] . 最终将创建长度为3的对象newArray,其中包含如下内容: newArray[0],[1],[2]

Am i doing this correctly, please do suggest me if anything wrong or a better way to do this. 我是否正确执行此操作,如果有任何错误或更好的方法,请提出建议。

Here's what you wrote (I think), just shortened a bit (and fixed the capitalization of variable names) 这是您写的(我认为),只是缩短了一点(并固定了变量名的大写字母)

var length = 3;
var newArray = [];
for( var i = 0 ; i < length ; i++ ) {
    newArray.push({newKey: 1});
}

but to be honest it's unclear to me exactly what you're trying to accomplish 但老实说,我不清楚您到底要完成什么

You could make it slightly more dynamic by referencing the variable for length. 您可以通过引用变量的长度使其动态性更高。

Example updated per comments: 每个评论更新示例:

var length = 3,
    newArray = [];

for ( var i=0; i<length; i++ ) {
    var tempObj = {};
    tempObj['newKey'] = 'SomeValue';
    newArray.push(tempObj);
}

I didn't really do more than clean up what you have. 除了清理您拥有的东西外,我并没有做更多的事情。

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

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