jQuery循环JSON问题

问题描述:

我尝试了几种组合,但被卡住了.任何帮助表示赞赏.我如何在这里阅读JSON记录(JSON的语法组织得井井有条吗?)我不断使用下面的代码或它的排列获取TypeError: Cannot read property '0' of undefined.

I tried a few combinations, but I am stuck. Any help is appreciated. How do I read the JSON record here please (is the syntax for the JSON organised well?) I keep getting TypeError: Cannot read property '0' of undefined with the code below and or permutations of it.

JSON:

{
  "wty_upgrade":[{
                    "wty":"Upgrade from 3 to 5 years", 
                    "mth":24, 
                    "pig":3000
                 }, 
                 {
                    "wty":"Upgrade from 3 to 10 years", 
                    "mth":84, 
                    "pig":8000
                 }]
}

代码:

function LoadWtyUpgPlans(wty) {

    var WtyRow = '';
    var WtyYears = '';

    for (var i = 0; i < wty.wty_upgrade[0].length; i++) { 
        WtyYears = wty.wty_upgrade[0].mth[i] / 12;
        WtyRow +='<tr> \
                    <td> \
                        <input type="hidden" class="smg-wty-up-val" value="' + wty.wty_upgrade[0].mth[i] + '"> \
                        ' + wty.wty_upgrade[0].wty[i] + ' \
                    </td> \
                    <td align="right">' + WtyYears + '</td> \
                    <td align="right">' + wty.wty_upgrade[0].pig[i] + '</td> \
                </tr>';
    };
};

您遇到了两个问题.

问题是您没有遍历数组,而是遍历了数组的第一个索引.其次,您正在尝试引用第m和头的索引.它们不是数组...

The problem is you are not looping through the array, you are looping through the first index of the array. Second, you are trying to reference the index of the mth and pig. They are not arrays...

function LoadWtyUpgPlans(wty) {

    var WtyRow = '';
    var WtyYears = '';
    var upgrades = wty.wty_upgrade;

    for (var i = 0; i < upgrades.length; i++) {
        console.log("wty: ", upgrades[i].wty);
        console.log("mth: ", upgrades[i].mth);
        console.log("pig: ", upgrades[i].pig);
    }

}