JavaScript - 当这些值相同时,如何使用print函数输出存储在数组中的2个值?

时间:2017-11-16 15:10:40

标签: javascript arrays innerhtml

var students = [
{
    name : "Dave",
    track : "Front End Development",
    achievement: 158,
    points: 14703
},
{
    name : "Jody",
    track : "iOS Development with swift",
    achievement: 133,
    points: 16303
},
{
    name : "Dave",
    track : "PHP Development",
    achievement: 55,
    points: 2023
},
{
    name : "Shawdesh",
    track : "Learn Wordpress",
    achievement: 40,
    points: 1950
},
{
    name : "Liton",
    track : "Rails Development",
    achievement: 98,
    points: 450
}
]

var student;
var message = [];
var search;

function print(message) {
document.getElementById('output').innerHTML = message;
}

function getStudentReport(student) {
var report = "<h3> Student: " + student.name + "</h3>"; 
report += "<p>Track: "+ student.track + "</p>";
report += "<p>achievement: "+ student.achievement + "</p>";
report += "<p>Points: "+ student.points + "</p>";
return report;
}

while(true) {
search = prompt("Search the student recoards: type a name [Jody] or (type quit to exit.)");
if (search == null || search.toLowerCase() == 'quit') {
    break;
} 
for (var i = 0; i < students.length; i += 1) {
    student = students[i];
    if (student.name.toLowerCase() === search.toLowerCase()) {
        message.push(getStudentReport(student));
    }  
}
for (var j = 0; j < message.length; j += 1) {
        document.write(message[j]);
    }           
}

当提示函数运行时,如果我写#Dave,则消息数组存储2个值,因为在#students数组中,Dave名称使用了两次。

但是当我通过print函数打印这个数组时,它只打印最后一个值。但是当我通过document.write打印它时会打印出2个值。

所以,现在我的问题是:如何使用#print函数打印存储在消息数组中的2个值?

1 个答案:

答案 0 :(得分:0)

当然,它会添加最后一条消息,因为您正在使用会覆盖内容的情感=,instea使用+=将新消息附加到旧内容,例如:

function print(message) {
    document.getElementById('output').innerHTML += message;
}

希望这有帮助。