簡體   English   中英

嵌套循環可動態創建對象

[英]Nested loop to dynamically create objects

我正在嘗試創建一個循環或嵌套循環,以創建包含許多對象的one(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];
};

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

// 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;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM