简体   繁体   中英

JavaScript - How can I use the print function to output 2 values that are stored in an array when those values are the same?

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]);
    }           
}

When the prompt function runs, if I write #Dave the message array stores 2 value because in #students Array the Dave name uses two times.

But when I print this array by print function it only prints the last value. But when I print it by document.write it prints 2 value.

So, now my question is: How can I print 2 values that are stored in a message array using my #print function?

Sure it will add just the last message since you're using affection = that will override the content, instea use += to append the new message to the old content, like :

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM