JavaScript:for循环中的else-if条件

时间:2015-06-04 19:59:49

标签: javascript

我无法理解代码中for循环下的else if语句中的条件。如果你能提供帮助,我真的很感激。

这是一个包含学生信息,姓名,学习跟踪,成就,分数的对象数组。我只需要帮助理解这个条件:i ===(students.length)-1

 var students = [ 
  { name: 'Dave', track: 'Front End Development', achievements: 158, points: 14730 },
  { name: 'Jody', track: 'iOS Development with Swift', achievements: 175, points: 16375 },
  { name: 'Jordan', track: 'PHP Development', achievements: 55, points: 2025 },
  { name: 'Jody', track: 'Learn WordPress', achievements: 40, points: 1950 },
  { name: 'Trish', track: 'Rails Development', achievements: 5, points: 350 }
];

var htmlMessage = '';
var student;
var search;
var notFound = [];

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

function getStudentReport( student ) {
  var report = '<h2>Student: ' + student.name + '</h2>';
  report += '<p>Track: ' + student.track + '</p>';
  report += '<p>Points: ' + student.points + '</p>';
  report += '<p>Achievements: ' + student.achievements + '</p>';
  return report;
}

while (true) {
  search = prompt('Search student records:\ntype a name Ex: Jody\n(or type "quit" to end)');
  if (search === '') {
    alert('Please enter a name to initiate search.')
  } else if (search === null || search.toLowerCase() === 'quit') {

      print('<h2>Thanks for using our student record search services.</h2><p>These names were not found : ' + 
            notFound.join(', ') + '</p>');
      break;
  }
  for (var i = 0; i < students.length; i++) {
    student = students[i];
    if (student.name.toLowerCase() === search.toLowerCase()) {
      htmlMessage = getStudentReport(student);
      print(htmlMessage);
      break;
    } else if (i === (students.length) -1){
        print('<p>' + search + ' was not found.</p>');
        notFound.push(search);
        break;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

else if是否检查循环结束并考虑搜索失败:

//if you are at the end of the array (searched through all students)
else if (i === (students.length) -1){
    //alert user that their search was not found
    print('<p>' + search + ' was not found.</p>');
    //push the failed search term into an array
    notFound.push(search);
    //break out of the loop, necessary because of the way the loop is 
    //written (while(true)) will go forever if not broken
    break;
}

...它是-1,因为数组第一项从0开始,而长度从1开始计数;-) 所以有一个差异为-1。

相关问题