2013-12-13 135 views
0

我試圖創建一個循環或嵌套的循環,這將創建一個(1)包含許多對象數組:嵌套循環動態創建對象

// example of the object structure 
obj0.country = distAttr[0]; 
obj0[municipo[0]] = econ[0]; 
obj0[municipo[1]] = edu[0]; 
obj0[municipo[2]] = gov[0]; 
obj0[municipo[3]] = health[0]; 
obj0[municipo[4]] = infra[0]; 
obj0[municipo[5]] = social[0]; 

obj1.country = distAttr[1]; 
obj1[municipo[0]] = econ[1]; 
obj1[municipo[1]] = edu[1]; 
obj1[municipo[2]] = gov[1]; 
obj1[municipo[3]] = health[1]; 
obj1[municipo[4]] = infra[1]; 
obj1[municipo[5]] = social[1]; 

// ... obj18 

這是我到目前爲止有:

// create all the objects, distAttr length is 19 
for (var i = 0; i < distAttr.length; i++) { 
    window['obj'+i ] = {}; 
}; 

// distName length is 6 
var number = distName.length; 

// this loop I can't figure out 
for (var j = 0; i < distName.length; j++) { 
    window['obj'+i ][municipo[j]] = econ[i]; 
}; 

// bind the objects to the array 
for (var i = 0; i < distAttr.length; i++) { 
    chartArray[i] = window['obj'+i]; 
}; 
+0

但是,什麼是你面臨的問題? – khalid13

+0

我在這裏看不到嵌套循環。 – brouxhaha

+0

我無法弄清楚如何建立與上面的例子具有相同結構的多個對象。窗口['obj'+ i] [municipo [j]] = econ [i];不會創建對象。 – Bwyss

回答

1

您可以在一個循環中建立的對象:

// Set up some variables and the field values you will use: 
var j, 
    obj, 
    ec = municipo[0], 
    ed = municipo[1], 
    go = municipo[2], 
    he = municipo[3], 
    in = municipo[4], 
    so = municipo[5]; 

// Loop through the array. 
for (i = 0; i < distAttr.length; i++) { 
    // Create an object with a country field. 
    obj = { country: distAttr[i] }; 
    // Populate the other fields. 
    obj[ec] = econ[i]; 
    obj[ed] = edu[i]; 
    obj[go] = gov[i]; 
    obj[he] = health[i]; 
    obj[in] = infra[i]; 
    obj[so] = social[i]; 
    // Set the array index to contain the object 
    // (and if you need it then create a global object `objx` 
    // - not sure if you need it though.) 
    chartArray[i] = window['obj'+i] = obj; 
}; 
+0

每次迭代都會替換'obj'的值,對吧? – DontVoteMeDown

+0

'obj'將在每次迭代中引用一個新對象,但是在迭代結束時'obj'被賦值爲'chartArray'的一個元素,所以保持在該數組中的引用不會丟失或被覆蓋。您將最終得到一個包含多個不同對象的數組(而不是多次覆蓋對象)。 – MT0

+0

是的,你說得對。 – DontVoteMeDown