javascript - 为什么我的 if、else if 和 else 语句不能正常工作?
问题描述
当我在数组中输入France
orfrance
时,在输入字段中输入国家/地区,代码块返回country not in our database
。我希望代码返回France is a country located in Europe
。
我尝试return
在每个条件语句上使用关键字,但没有成功。我还阅读了w3schools.com 关于if
/ else
statement的文档。
但是,我仍然无法解决这个问题。有趣的是,该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>
解决方案
如前所述,您的循环不会因找到结果而中断。此外,值得考虑完全取消循环并使用数组函数“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";
推荐阅读
- sql - 使用基于联接的值创建组列
- java - 如何在一个参数中查找多个项目 Spring data jpa
- r - 转换频率数据以用于 R 中的逻辑回归
- regex - 根据同一行中不同列的值拆分一个 Pandas 列?
- python-3.x - 使用 for 循环获取 Pandas 系列索引级别
- python-3.x - 如何创建附加主题建模可视化?
- c++ - 使用 SysNative 在 Visual Studio 中创建 64 位应用程序
- php - PHPExcel+MySQL 每行导出
- google-apps-script - 如何将 Google Apps Script Web 应用程序发布到 G-Suite Marketplace?
- ios - EXC_CORPSE_NOTIFY 终止原因:命名空间 SPRINGBOARD