为什么我的循环获取对象属性值不起作用?

时间:2015-11-10 16:50:46

标签: javascript loops

我正在开发一个搜索程序,用户可以在提示框中键入名称,如果它与object属性中的属性名称匹配,则它只显示该属性值。但即使我在对象中输入正确的名称,它也不会显示值。

var students = [
{
    name: "secil inam",
    track: "front-end web development",
    achievements: 8,
    points: 501
} //an example object i actually have 5 of these
]


var msg = '<div id="home"><ol>';

while(true){ // this loop displays the prompt
var search = prompt("search for a student  name, type quit to exit.");


if( search.toLowerCase() === "quit" || search === null){ // doesn't break if it's null
    break;
}
else
{    
    for(var i = 0; i < students.length; i++){

        if(students[i].name === search){

            for(var key in students[i]){ //this doesn't seem to work
                    msg += '<li>' + key + ': ' + students[i][key] + '</li>';
            }
             break;   
        }
         console.log(i); //this runs
    }
 }

}

msg += '</ol></div>';

document.write(msg);

请告知。

1 个答案:

答案 0 :(得分:2)

在空对象上调用toLowerCase()会导致错误,您应该在while循环中切换条件的顺序。

if(search === null || search.toLowerCase() === "quit"){
    break;
}

进行这些更改后,它似乎有效:http://jsfiddle.net/3pjm7sfc/1/