【问题标题】:Why is the logical 'OR' not working on my second 'IF' condition?为什么逻辑 \'OR\' 在我的第二个 \'IF\' 条件下不起作用?
【发布时间】: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


    【解决方案1】:

    我刚刚重新运行了您的代码,您的代码运行良好。这是输出=>

    兄弟,你多大了?18 兄弟,你最喜欢的食物是什么?炸鱼条 你才 18 岁还吃鱼指?? 那是蹩脚的兄弟,长大了。 欢迎来到 Programiz!

    也许,您在输入中输入了错字;或者你可能放了双倍空格之类的东西。但是 ||声明正在按应有的方式工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 2019-08-15
      相关资源
      最近更新 更多