You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:39:02