gpt4 book ai didi

javascript - 为什么我的 if、else if 和 else 语句不能正常工作?

转载 作者:行者123 更新时间:2023-12-05 08:22:06 25 4
gpt4 key购买 nike

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

我已经尝试在每个条件语句中使用 return 关键字但没有成功。我也读过 w3schools.com's documentation on 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";

关于javascript - 为什么我的 if、else if 和 else 语句不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65520662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com