首页 > 解决方案 > 为什么我的 if、else if 和 else 语句不能正常工作?

问题描述

当我在数组中输入Franceorfrance时,在输入字段中输入国家/地区,代码块返回country not in our database。我希望代码返回France is a country located in Europe

我尝试return在每个条件语句上使用关键字,但没有成功。我还阅读了w3schools.com 关于if/ elsestatement的文档。

但是,我仍然无法解决这个问题。有趣的是,该else if声明有效。我的意思是当我将输入字段留空然后单击代码确实返回的按钮时field cannot be left blank。我知道我的问题可能听起来很基本,但我仍然是初学者。

const btn = document.getElementById("button");

btn.addEventListener("click", function(){
  fetch("https://restcountries.eu/rest/v2/all")
  .then(function(response){
    return response.json()
  })
  .then(function(data){
    var userInput = document.getElementById("userInput");
    var userInputValue = userInput.value;
    var region = document.getElementById("region");
    for(var i = 0; i < data.length; i++) {
      if(userInputValue.toLowerCase() === data[i].name.toLowerCase()) {
        region.innerHTML = `${data[i].name} is a country located in ${data[i].region}`
      } else if (userInputValue === "") {
        region.innerHTML = "field cannot be left blank";
      } else {
        region.innerHTML = "country not in our database";
      }
    }
  })
})
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>API Beginners</title>
  </head>
  <body>
    <label for="userInput">country's name</label>
    <input id="userInput" type="text" name="" value="" placeholder="enter a country"><br>
    <label for="button">clik here to submit</label>
    <button id="button" type="click" name="button">click me</button>
    <div id="region"></div>

  </body>
  <script src="index.js" type="text/javascript"></script>
</html>

标签: javascriptif-statement

解决方案


如前所述,您的循环不会因找到结果而中断。此外,值得考虑完全取消循环并使用数组函数“find”:

var existing = data.find(d => d.name.toLowerCase() === userInputValue.toLowerCase());
region.innerHTML = existing 
    ? `${existing.name} is a country located in ${existing.region}`
    : userInputValue === ""
        ? "field cannot be left blank"
        : "country not in our database";

推荐阅读