【问题标题】:why wont "||" (or) work in my javascript function?为什么不会“||” (或)在我的 javascript 函数中工作?
【发布时间】:2020-06-18 20:37:27
【问题描述】:

我正在尝试编写代码,以便如果给出 2 个代表我的生日(月 = 11,日 = 3)的数字,它将记录“你怎么知道”。其他任何事情都会返回“又一天”。也需要月份和日期的顺序无关紧要。

我把它写成:

function birthday (month,day){
  let result;
  if( month == "11" && day == "3") || (day == "3" && month = "11"){
      result = "How did you know?";
     }
      else {
       result = "Just Another Day";
      }
  return result;
}

console.log(birthday(3, 11));

但它会返回并告诉我 || (或)是一个意外的标记......我还能怎么写?

【问题讨论】:

    标签: javascript if-statement operators


    【解决方案1】:

    || 运算符的两侧有两个条件,它们表示完全相同的内容。在第二个条件下,您需要检查 day 是否为 11 并且 month 是否为 3。此外,您在最后一个比较中使用 = 运算符而不是 @987654323 @:

    if ((month == "11" && day == "3") || (month == "3" && day == "11")) {
    

    【讨论】:

    • @Berto99 是的,很好。谢谢。已编辑和修复。
    【解决方案2】:

    我修改了你的代码,最后一个比较符号 (==) 是错误的,它是一个赋值符号 (=) 并且你正在比较两次日期和月份,现在你的代码可以正常工作了!

    function birthday (month, day){
      let result = "";
    
      if(( month == "11" && day == "3") || (month == "3" && day == "11")){
          result = "How did you know?";
         }
          else {
           result = "Just Another Day";
          }
      return result;
    }
    
    console.log(birthday(3, 11));

    【讨论】:

      【解决方案3】:

      您应该在 if 之后添加“(”,在 (day == "3" && month == "11") 之后添加“)”。还将最后一次比较的 = 运算符更改为 ==,并将最后一次比较从 (day == "3" && month == "11") 更改为 (month == "3" && day == "11")。将您的代码更改为此代码:

      function birthday (month,day){
            let result;
            if( (month == "11" && day == "3") || (month == "3" && day == "11")){
                result = "How did you know?";
               }
                else {
                 result = "Just Another Day";
                }
            return result;
          }
          
          console.log(birthday(3, 11));

      【讨论】:

        猜你喜欢
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        • 2011-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-01
        • 2022-01-15
        相关资源
        最近更新 更多