javascript从字符串嵌套for循环(多个层)

时间:2018-01-17 12:00:45

标签: javascript arrays string object

我有一个我试图循环的字符串。它有嵌套数组,我想从每一层获取值。然而,我似乎从第二层开始未定义。

// String <authorization xdt:Transform="Insert"> <allow roles = "Domain\UserGroup" /> <deny users="*" /> </authorization>

//我的for循环 - 所有变量都在之前声明

[{"username":"test","usersurname":"test","cellnumber":"test","displayname":"test","profilepicture":"test","projects":[{"projectname":"test","dateadded":"test","notes":"test","image":"test"},{"task":[{"taskname":"test","taskdescription":"test","taskimage":"test"}]}]}]

1 个答案:

答案 0 :(得分:1)

请检查代码中未定义的结束错误。如果某些东西未定义,循环就会中断。

for (var i = 0; i < data.length; i++) {
        username = data[i].username;
        console.log(username);
        usersurname = data[i].usersurname;
        cellnumber = data[i].cellnumber;
        displayname = data[i].displayname;
        profilepicture = data[i].profilepicture;
        if("undefined" != typeof (data[i].projects))
        {
            for (var j = 0; j < data[i].projects.length; j++) {
                dateadded = data[i].projects[j].dateadded;
                console.log(dateadded);
                notes = data[i].projects[j].notes;
                image = data[i].projects[j].image;
                if ("undefined" != typeof (data[i].projects[j].task)) {
                    for (var k = 0; k < data[i].projects[j].task.length; k++) {
                        taskname = data[i].projects[j].task[k].taskname;
                        console.log(taskname);
                        taskdescription = data[i].projects[j].task[k].taskdescription;
                        taskimage = data[i].projects[j].task[k].taskimage;
                    }
                }
            }
        }

    }