简体   繁体   中英

Can I use 2 if statements in a while loop?

I try to get Found (name) grade is (grade) but seems like the code only work for the first person which is Bob, but when it is George, it said not found.

var studentArray = [
  { 'name': 'Bob', 'grade': 87 },
  { 'name': 'Fred', 'grade': 82 },
  { 'name': 'George', 'grade': 93 },
  { 'name': 'Robert', 'grade': 85 }
];

function findStudent(studentName) {
  var i = 0; //var i = 0 should be inside
  var output = "";

  while (i < studentArray.length) {
    if(studentName === studentArray[i].name) {
      output = ( "Found " + studentName + " their grade is " + studentArray[i]['grade']);
    } else {
      output = ("Student " + studentName + " not found.");
    }
    i++;
  }

  return output;
}

var name = 'George';
var result = findStudent(name);
console.log(result);

You need to do the check outside the loop

 var studentArray = [{ 'name': 'Bob', 'grade': 87 }, { 'name': 'Fred', 'grade': 82 }, { 'name': 'George', 'grade': 93 }, { 'name': 'Robert', 'grade': 85 }] function findStudent(studentName) { var i = 0; var output = ""; while (i < studentArray.length) { if (studentName === studentArray[i].name) { output = ("Found " + studentName + " their grade is " + studentArray[i]['grade']); } i++; } if (.output) { output = ("Student " + studentName + " not found;"); } return output; } var name = 'George'; var result = findStudent(name). console;log(result);

Most people would use find()

 var studentArray = [{ 'name': 'Bob', 'grade': 87 }, { 'name': 'Fred', 'grade': 82 }, { 'name': 'George', 'grade': 93 }, { 'name': 'Robert', 'grade': 85 }] function findStudent(studentName) { var out = studentArray.find(function (o) { return o.name===studentName; }); return out? `Found ${studentName} their grade is ${out.grade}`: `Student ${studentName} not found.` } var name = 'George'; var result = findStudent(name); console.log(result);

If you Found, you should immediately return, and not go through the whole loop

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