我仍然不确定如何使用if语句。
研究和解释。我所知道的是它搜索那个需要回答的特定陈述。
无论如何我有一个while循环运行读取记录。
它要求用户输入一个邮政编码,现在我只想让它搜索记录,只打印出与用户输入的邮政编码相匹配的邮政编码。
我没有收到通过指定记录搜索的特定邮政编码的任何错误或打印件。
records = openZipCodeStudyRecordSet();
userEntered = prompt("Search students in current zipcode:");
while (records.readNextRecord()) {
// This IF only in place for this particular example program
// Remove the IF to work with the entire file
firstName = records.getSampleFirstName();
lastName = records.getSampleLastName();
gender = records.getSampleGender();
zipCode = records.getSampleZipCode();
for (counter = 0; counter <records.length; counter++) {
if(userEntered == records[counter].length){
zipCode += records[counter];
}
}
allDisplayRows += "<tr><td>" + firstName + "</td>"
+ "<td>" + lastName + "</td><td>" + gender
+ "</td><td>" + zipCode + "</td></tr>";
count++;
}
我很困惑为什么它不会将它与记录进行比较。是我的for循环,如果循环正确吗?
我觉得我做错了。
答案 0 :(得分:1)
records.readNextRecord()
不返回邮政编码,它只是转到下一条记录,所以在循环中调用它并将其与userEntered
进行比较是没有意义的。您应该将其与您从记录中获得的邮政编码进行比较。
while (records.readNextRecord()) {
zipCode = records.getSampleZipCode();
if (userEntered == zipCode) {
firstName = records.getSampleFirstName();
lastName = records.getSampleLastName();
gender = records.getSampleGender();
break;
}
}
console.log(zipCode, firstName, lastName, gender);
如果您需要查找包含邮政编码的所有记录,则应将匹配项放入数组中,而不是使用break
。
results = [];
while (records.readNextRecord()) {
zipCode = records.getSampleZipCode();
if (userEntered == zipCode) {
results.push({
zipCode: zipCode,
firstName: records.getSampleFirstName(),
lastName: records.getSampleLastName(),
gender: records.getSampleGender()
};
}
}
console.log(results);