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

如何在JavaScript中匹配用户输入与数组数据?代码问题排查

问题分析与解决方案

问题根源

你代码里的核心错误是用String.match(cities)来判断输入是否匹配城市数组:

  • match()方法要求参数是正则表达式,不是数组。当你传入数组时,JS会自动把数组转成逗号分隔的字符串(比如"Banda Aceh,Bandar Lampung,..."),再当作正则使用,这完全不符合你的匹配需求,所以永远会走到else分支。
  • 另外,你没处理输入为空的场景,也没有在每次搜索前隐藏之前的结果,多次点击会导致多个提示同时显示。

修复后的代码

JavaScript

function searchRespond() {
  // 缓存DOM元素,避免重复查询DOM树
  const input = document.getElementById("myInput");
  const areaCovered = document.getElementById("areaCovered");
  const areaNotCovered = document.getElementById("areaNotCovered");
  const fillArea = document.getElementById("fillArea");
  const searchResult = document.getElementById("searchResult");
  
  // 先隐藏所有提示框,避免重叠显示
  areaCovered.style.display = "none";
  areaNotCovered.style.display = "none";
  fillArea.style.display = "none";

  const inputValue = input.value.trim();
  if (!inputValue) {
    // 处理输入为空的情况
    fillArea.style.display = "block";
    return;
  }

  // 用数组includes方法判断是否存在(严格匹配大小写)
  if (cities.includes(inputValue)) {
    areaCovered.style.display = "block";
  } else {
    areaNotCovered.style.display = "block";
    searchResult.textContent = inputValue;
  }
}

const cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];

CSS

.HeadlineSearchContainer {
  position: relative;
  top: 100px;
  margin: auto;
  height: 159px;
}

.SearchCharacterStyle {
  font-family: Roboto;
  font-size: 12px;
  line-height: 24.82px;
  text-align: left;
}

.searchrespond {
  font-family: Roboto;
  font-size: 12px;
  line-height: 24.82px;
  text-align: left;
}

#areaCovered {
  display: none;
}

#areaNotCovered {
  display: none;
}

#fillArea {
  display: none;
}

HTML

<div class="HeadlineSearchContainer">
  <div class="SearchCharacterStyle">
    <h>SEARCH FOR AREA COVERANGE</h>
  </div>
  <div id="mySearch" class="searchbox_box">
    <form autocomplete="off" name="myForm">
      <div class="autocomplete" style="width:300px;">
        <input id="myInput" type="text" name="city" placeholder="Enter Your Destination City">
        <i class="searchbutton"></i>
      </div>
      <input type="button" formtarget="_new" onclick="searchRespond()" name="input" value="Search">
      <div class="searchrespond" id="searchRespond">
        <h id="areaCovered">YES! We cover your area destination</h>
        <h id="areaNotCovered">We don't cover your area destination yet
          <p id="searchResult"></p>
        </h>
        <h id="fillArea">Please fill your area destination first</h>
      </div>
    </form>
  </div>
</div>

优化建议

  1. 大小写不敏感匹配:如果希望用户输入bandung也能匹配Bandung,可以用some()方法统一转小写判断:
    const isMatch = cities.some(city => city.toLowerCase() === inputValue.toLowerCase());
    
  2. 替换内联事件监听:内联onclick不利于代码维护,建议用DOM事件监听替代:
    document.querySelector('input[type="button"]').addEventListener('click', searchRespond);
    
    然后删掉HTML里的onclick="searchRespond()"。
  3. 实时搜索提示:如果要提升用户体验,可以监听输入框的input事件,实时渲染匹配的城市列表,让用户不用点击搜索就能看到结果。

内容的提问来源于stack exchange,提问作者Escade

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:35:23