开发者问题收集

未捕获的类型错误:无法读取未定义的属性 x

2013-10-10
14091

在实际脚本运行并生成正确输出时,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个回答

for 循环条件不正确。

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

查看小提琴 http://jsfiddle.net/wJUeP/7/

Abhidev
2013-10-10

错误在这里:

j = data[0].weekending.length

这将返回 10,即 weekending 属性中字符串的长度 == 10 ("09/10/2013") 我认为你需要的是这个:

j = data[0].jobs.length
jasonscript
2013-10-10