【问题标题】:Multiple i"if" values? [duplicate]多个 i"if" 值? [复制]
【发布时间】:2020-01-17 00:47:46
【问题描述】:

我已经制作了我的第一个 js 脚本,我想知道,是否可以将多个值添加到 "if var =="

var day = window.prompt("How was your day? Describe it in 1 word!");

if (day == null, "bad", "terrible") {
    document.write("How come?");
} else {
    document.write("sounds great");
}

我希望它仅在 var day 糟糕或糟糕的情况下给出不同的响应。不适用于任何其他回复!

但输出只有

【问题讨论】:

  • 广告多重条件或使用in_array
  • 非常感谢!这是我第一次使用 js,所以感谢您的快速响应!
  • @DevsiOdedra javascript 中没有“in_array”。在他的情况下,他可以使用indexOfincludes(或最终使用any)。 in_array 存在于 php 中,而不存在于 javascript 中。

标签: javascript


【解决方案1】:
if (day == null || day == "bad" || day == "terrible") {
    document.write("How come?");
} else {
    document.write("sounds great");
}

【讨论】:

    【解决方案2】:

    您可以使用switch 语句。

    switch (day) {
      case "bad":
      case "terrible":{ document.write("How come?"); } break;
      default: { document.write("sounds great"); } break;
    }
    

    所以,在你的情况下:

    var day = window.prompt("How was your day? Describe it in 1 word!");
    switch (day) {
       case "bad":
       case "terrible":{ document.write("How come?"); } break;
       default: { document.write("sounds great"); } break;
    }

    【讨论】:

    • 为什么 case 语句部分中的块语句?
    • 因为我想他不会只写一行代码。
    • What do the curly braces do in switch statement after case in es6?一直在用,不知道是不是一个好习惯,这可能是一个很好的问题。
    • @Alessandro 不,这不是一个好问题。它主要基于意见,因此应该关闭。
    • @VLAZ,它不是基于选项的,在这种情况下是多余的,因为没有局部变量。
    猜你喜欢
    • 1970-01-01
    • 2012-06-18
    • 2017-07-06
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 2020-11-25
    相关资源
    最近更新 更多