Javascript 如何在循环中创建动态对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2383484/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:02:01  来源:igfitidea点击:

How to create a dynamic object in a loop?

javascriptloopsobject

提问by mike

Basically I want to create one large object of many object in JavaScript. Something like:

基本上我想在 JavaScript 中创建一个包含多个对象的大对象。就像是:

var objects = {}
for (x)
objects.x = {name: etc}

Any ideas?

有任何想法吗?

回答by Tomalak

var objects = {};

for (var x = 0; x < 100; x++) {
  objects[x] = {name: etc};
}

回答by John K

An actual implementation

一个实际的实现

Populate a container object with 100 other objects.

用 100 个其他对象填充一个容器对象。

<script>
var container = { }; // main object

// add 100 sub-object values
for(i = 0; i < 100; ++i) {
 container['prop'+i ]  /*property name or key of choice*/
         = { 'a':'something', 
             'b':'somethingelse', 
             'c': 2 * i
           }; 
}

TEST THE Results - iterate and display objects...

测试结果 - 迭代和显示对象...

for(var p in container) {
 var innerObj = container[p];
 document.write('<div>container.' + p + ':' + innerObj + '</div>');
 // write out properties of inner object
 document.write('<div> .a: ' + innerObj['a'] + '</div>');
 document.write('<div> .b: ' + innerObj['b'] + '</div>');
 document.write('<div> .c: ' + innerObj['c'] + '</div>');
}
</script>

Output is like

输出就像

container.prop0:[object Object]
.a: something
.b: somethingelse
.c: 0
container.prop1:[object Object]
.a: something
.b: somethingelse
.c: 2
container.prop2:[object Object]
.a: something
.b: somethingelse
.c: 4

etc...

等等...

回答by streetparade

Try this

尝试这个

var objects = new Array();
var howmany = 10;

for (var i = 0; i < howmany; i++)
{
    objects[i] = new Object();

}