开发者

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 eventuall开发者_Go百科y create newArray of Objects whose length is 3 containing something like this.. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜