添加else分支后If-else语句不生效,通讯录搜索功能仅显示无匹配结果
通讯录搜索功能问题修复
问题原因
- 循环结束后无条件执行
resultsContent.text('None found'),直接覆盖了匹配成功时写入的联系人内容 - 原有逻辑在匹配到多个联系人时,只会保留最后一个匹配项的内容,前面的结果会被依次覆盖
修复代码
单匹配结果版本(找到第一个匹配项后终止搜索)
$(document).ready(function(){ newSearch.click(function(){ const inputValue = $('#searchcontacts').val().toUpperCase(); let result = 'None found'; for(let i = 0; i < contactList.length; i++){ if(inputValue === contactList[i].firstName.toUpperCase()){ result = contactList[i].firstName + " " + contactList[i].lastName + " " + contactList[i].phoneNumber + " " + contactList[i].addressText; break; // 匹配到第一个结果就退出循环,不需要继续遍历 } } resultsContent.text(result); }); });
多匹配结果版本(展示所有符合条件的联系人)
$(document).ready(function(){ newSearch.click(function(){ const inputValue = $('#searchcontacts').val().toUpperCase(); let resultList = []; for(let i = 0; i < contactList.length; i++){ if(inputValue === contactList[i].firstName.toUpperCase()){ resultList.push(contactList[i].firstName + " " + contactList[i].lastName + " " + contactList[i].phoneNumber + " " + contactList[i].addressText); } } resultsContent.text(resultList.length ? resultList.join('\n') : 'None found'); }); });
内容的提问来源于stack exchange,提问作者Archer16
相关产品推荐
相关产品推荐

