2014-01-09 126 views
0

下面是代碼現在的樣子,行數少,屬性少。如何循環創建對象?

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

如果可能,我該如何做到這一點?

+0

10億行變量?不確定JavaScript會處理那麼多的對象。你只需要一個對象數組?樣本1應該工作。在第二個代碼示例中,將整數推送到數組。然後嘗試添加一個屬性。整數不能有其他屬性。 –

回答

1
var rows = []; 
for(var i = 0; i < 7; i++) 
{   
    rows.push(new Object()); 
} 
rows[0].name = "Hello World!"; 
alert(rows[0].name); 
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/