jQuery循环JSON问题 [英] jQuery Loop JSON Issue

查看:88
本文介绍了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);
    }

}

这篇关于jQuery循环JSON问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆