未捕获的TypeError:无法读取未定义的属性x

时间:2013-10-10 07:18:07

标签: javascript xml json

当实际脚本正常工作并生成正确的输出时,在Chrome控制台中获取上述错误,想知道如何摆脱此错误以及导致错误的原因。

JSFiddle:http://jsfiddle.net/wJUeP/

HTML代码:

<ul id="menu"></ul>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

JS代码:

$(function(){
var data = [{"weekending":"09\/10\/2013","jobs":[{"jobnumber":"1001","jobaddress":"Test1001","employees":[{"employeenumber":"1","name":"James Blabla","class":"FHM","notes":"xx","nt-wkmon":"2","t12-wkmon":"5","dt-wkmon":"4","status-wkmon":"Public Holiday","startTime-wkmon":"4","finishTime-wkmon":"6","nt-wktue":"7"}]},{"jobnumber":"1002","jobaddress":"Test1002","employees":[{"employeenumber":"1","name":"Cameron Le","class":"FHQ","notes":"xx","nt-wkmon":"2","t12-wkmon":"5","dt-wkmon":"4","status-wkmon":"Public Holiday","startTime-wkmon":"4","finishTime-wkmon":"6","nt-wktue":"7"},{"employeenumber":"2","name":"David Le","class":"FHQ","notes":"xx","nt-wkmon":"2","t12-wkmon":"5","dt-wkmon":"4","status-wkmon":"Public Holiday","startTime-wkmon":"4","finishTime-wkmon":"6","nt-wktue":"7"}]},{"jobnumber":"1003","jobaddress":"Test1003","employees":[{"employeenumber":"1","name":"Nick G","class":"sdf","notes":"sdf","nt-wkmon":"2","t12-wkmon":"5","dt-wkmon":"4","status-wkmon":"Public Holiday","startTime-wkmon":"4","finishTime-wkmon":"6","nt-wktue":"7"}]}]}];

for(var i = 0, j = data[0].weekending.length; i<j; i++) {
    rootMenu = data[0].jobs[i];
    $("#menu").append("<li id='job_" + rootMenu.jobnumber + "'>" + rootMenu.jobnumber);
    if(rootMenu.hasOwnProperty("employees")) {
        $("#menu").append("<ul id='employees_job_" + rootMenu.jobnumber + "'>");
        for(var n = 0, m = rootMenu.employees.length; n<m; n++) {
            var subMenu = rootMenu.employees[n];
            if(subMenu.hasOwnProperty("name")) {
                $("#employees_job_" + rootMenu.jobnumber).append("<li>" + subMenu.name + "</li>");
            }
        }
        $("#menu").append("</ul>");
    } else {
        $("#menu").append("</li>");
    }
}
});

注意:我仍处于应用程序的开发阶段,我可以灵活地更改和操作数据结构,如果嵌入的JSON数据看起来很糟糕我可以更改它,实际数据存储在XML文件中然后由PHP读取并输出为JSON。

2 个答案:

答案 0 :(得分:1)

for循环条件不正确。

您已使用等于10的j = data[0].weekending.length并且您正在迭代只有3个作业的data[0].jobs对象。您在作业上迭代次数超过3次,因此您收到错误。

结帐小提琴http://jsfiddle.net/wJUeP/7/

答案 1 :(得分:0)

错误在于:

j = data[0].weekending.length

这是返回10,这是周末属性中字符串的长度== 10(“09/10/2013”​​) 我认为你需要这个:

j = data[0].jobs.length