如何循环创建对象?

时间:2014-01-09 21:07:08

标签: javascript arrays for-loop properties

下面是代码现在的样子,行数少,属性少。

var row1 = new Object();
var row2 = new Object();
var row3 = new Object();
var row4 = new Object();
var row5 = new Object();
var row6 = new Object();
var row7 = new Object();
row1.name = "Hello World!";
alert (row1.name);

下面的代码没有按预期工作,因为行不是原始的,但我需要做这样的事情,因为我有十亿行变量。

var row = [];
var row1 = [];
var row2 = [];
var row3 = [];
row.push(1); 
row[1].name = "Hello World";
alert(row[1].name);

如果可能的话,我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

var rows = [];
for(var i = 0; i < 7; i++)
{        
    rows.push(new Object());
}
rows[0].name = "Hello World!";
alert(rows[0].name);

答案 1 :(得分:0)

您可以在javascript中创建自定义复杂对象,如下所示:

//complex object
ComplexObj = function(){
    var self = {
        'prop1': 'value1',
        'prop2': 'value2',
        'prop3': {
            'subprop1': 'subvalue1',
            'subprop2': 'subvalue2'
        },
        'prop4': [
            1, 2, 3, 4
        ]
    };

    return self;
};

//code that creates instances of the complex object
var rows = [];
var newObj1 = new ComplexObj();
newObj1.prop1 = 'newvalue1';

var newObj2 = new ComplexObj();
newObj2.prop3.subprop2 = 'newsubvalue2';

rows.push(newObj1);
rows.push(newObj2);

for (var i = 0; i < rows.length; i++){
    alert('row' + i + ': prop1=' + rows[i].prop1 + ' subprop2=' + rows[i].prop3.subprop2);
}

您可以在此处查看演示。请注意,我更新newObj1.prop1和newObj2.prop3.subprop2以显示newObj1和newObj2是ComplexObj的不同实例。

http://jsfiddle.net/p5evg/1/