【问题标题】:Validate Zipcode and Print State when Zipcode is found找到邮政编码时验证邮政编码和打印状态
【发布时间】:2021-06-12 17:42:35
【问题描述】:

此应用程序的主要目标是提供邮政编码搜索,然后在找到邮政编码后显示与该邮政编码相关联的状态。如何修改此代码以反映我想要实现的目标?

    <input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip()"/>
<div id="msg"></div>

    function checkIfAvailable(zip)
{
  let zones = [["90210","Beverly Hills"],
              ["90211","BH"]]
  return( zones.indexOf(zip) >= 0 )
}

function validateZip()
{
  let zip = document.getElementById("zipCode").value;
  let msg =""
  if(checkIfAvailable(zip)
    {
      msg="Our service is available in" + State
     ;
    }
   else
     {
       msg="Sorry our service is not available in this area";
     }
    document.getElementById("msg").innerHTML = msg;
}

【问题讨论】:

    标签: javascript zipcode


    【解决方案1】:

    如果您可以将array 更改为object,那么简单如下:

    let zones = {90210: "Beverly Hills", 90211:"BH"};
    let msgElement = document.getElementById("msg")
    
    function validateZip(userInput) {
      if (userInput.value in zones) {
         msgElement.innerHTML = "Our service is available in " + zones[userInput.value];
      } else {
        msgElement.innerHTML = "Sorry our service is not available in this area";
      }
    }
    <input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip(this)"/>
    <div id="msg"></div>

    【讨论】:

      【解决方案2】:

      checkIfAvailable 可以使用find 返回内部数组(如果存在):

      function checkIfAvailable(zip) {
          let zones = [...];
          // Find an inner array where the first element [0]
          // is the zip
          return zones.find(item => item[0] === zip);
      }
      

      然后在validateZip:

      const zone = checkIfAvailable(zip);
      if (zone) {
          // zone will be the matching inner array
          // such as ["90210", "Beverly Hills"]
          const State = zone[1];
          msg = "Our service is available in " + State;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-09-08
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        • 2013-10-09
        • 2018-07-21
        • 1970-01-01
        • 2022-12-11
        • 1970-01-01
        相关资源
        最近更新 更多