【发布时间】:2023-02-09 18:24:18
【问题描述】:
我正在学习“if..else”和逻辑运算符。我写了一些代码来帮助我学习,这就是全部;
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Function scope example</title>
</head>
<body>
<button>Press me</button>
<script>
const button = document.querySelector("button");
function greet() {
let name = prompt("What is your name?");
alert(`Hello ${name}, nice to see you!`);
let age = prompt(`${name}, how old are you?`);
let favoriteFood = prompt(`${name}, what\'s your favorite food?`)
if (favoriteFood == 'Fish fingers' || favoriteFood == 'fish fingers'){
if (age > 16){
alert(`You\'re ${age} and you eat ${favoriteFood}??`)
alert("That's lame " + name + ", grow up.")
} else if(age<16){
alert('Yummy kiddo!')
}
}if(favoriteFood == 'Ham' || favoriteFood == 'ham'){
alert('That\'s Ponyos favorite food too!')
}else if(favoriteFood == 'Cheese' || favoriteFood == 'cheese'){
alert('Cheese is good for the soul')
}else {
alert(`Cool, ${name}, that sounds yum!`)
}
button.addEventListener("click", greet);
</script>
</body>
</html>
这是没有按预期工作的部分;
if (favoriteFood == 'Fish fingers' || favoriteFood == 'fish fingers'){
if (age > 16){
alert(`You\'re ${age} and you eat ${favoriteFood}??`)
alert("That's lame " + name + ", grow up.")
} else if(age<16){
alert('Yummy kiddo!')
}
第一个条件“Fish fingers”在输入提示时起作用,并根据“age”运行以下代码,但第二个条件“fish fingers”不起作用。它跳到最后的“else”。
我预计当在提示中输入“Fish fingers”或“fish fingers”时,以下代码会运行但不会运行。
我已经尝试再次阅读所有内容并使用返回预期结果的沙箱进行游戏。这是非常不同的代码,但使用“OR”的方式是相同的。
我哪里错了? TIA
【问题讨论】:
标签: function if-statement conditional-statements logical-operators