代码之家  ›  专栏  ›  技术社区  ›  teacosts

如何用第三个响应来回答我的JavaScript问题?

  •  -3
  • teacosts  · 技术社区  · 5 年前

    我正在学习JavaScript,我创建了一个简单的脚本,它会问你工作了多少小时。然后,它将显示您是否工作足够,然后显示您之前输入的号码。

    我做了前两行

    if (hours > 18) {
        alert('You have worked enough hours, thank you,');
    } else if (hours < 18) {
        alert('You have not worked enough hours.');
    }
    

    效果很好。但随后我添加了第三行:

    else if (hours > 30) {
        alert('Wow, you have worked a lot of hours!');
    }
    

    这行不通。

    可能有什么问题?我将在这里留下完整的剧本:

    'use strict';
    
    let hours = prompt('How many hours have you worked today?');
    
    if (hours > 18) {
      alert('You have worked enough hours, thank you,');
    } else if (hours < 18) {
      alert('You have not worked enough hours.');
    } else if (hours > 30) {
      alert('Wow, you have worked a lot of hours!');
    }
    
    alert(`You have worked ${hours} hours`);
    3 回复  |  直到 5 年前
        1
  •  1
  •   Dcoder14    5 年前

    首先,你必须检查小时数是否大于30,然后你必须检查18,因为首先如果你检查 hours > 18 然后,当您输入的小时数超过18小时(也包括大于30小时)时,它将始终为真,因此您的支票 else if (hours > 30) 从不执行。

    <!DOCTYPE>
     <html>
       <script>
    
         'use strict';
    
          let hours = prompt('How many hours have you worked today?');
    
          if (hours > 30) {
             alert('Wow, you have worked a lot of hours!');
          }
          else if (hours >= 18) {
             alert('You have worked enough hours, thank you,');
          }
          else if (hours < 18) {
             alert('You have not worked enough hours.');
          }
    
         alert(`You have worked ${hours} hours`);
    
      </script>
    </html>
    
        2
  •  0
  •   Albert Nguyen    5 年前

    您需要先检查条件“小时数>30”。 希望下面的代码对你有所帮助

    <!DOCTYPE>
    <html>
    
    <script>
    
        'use strict';
    
        let hours = prompt('How many hours have you worked today?');
        if (hours > 30) {
    
            alert('Wow, you have worked a lot of hours!');
        } 
        else if (hours > 18) {
    
            alert('You have worked enough hours, thank you,');
        }
    
        else if (hours < 18) {
    
            alert('You have not worked enough hours.');
        }
    
        alert(`You have worked ${hours} hours`);
    
        </script>
    
    </html>
    
    
        3
  •  0
  •   Shawn Xiao    5 年前

    你应该搬走 if (hours >= 30) 一开始,先检查一下。 否则,它将包含在条件中 if (hours >= 18) 永远不会被处决。

    <!DOCTYPE>
    <html>
    
    <script>
    
        'use strict';
    
        let hours = prompt('How many hours have you worked today?');
    
        if (hours >= 30) {
    
            alert('Wow, you have worked a lot of hours!');
        }
        else if (hours >= 18) {
    
            alert('You have worked enough hours, thank you,');
        }
        else {
    
            alert('You have not worked enough hours.');
        }
    
        alert(`You have worked ${hours} hours`);
    
        </script>
    
    </html>