【问题标题】:Or condition never evaluates to true或者条件永远不会评估为真
【发布时间】:2015-04-23 01:15:47
【问题描述】:

这个 javascript 代码运行成功,但我认为它没有通过它的“else”语句,因为它不打印它的控制台......为什么?

 i = 0;
    for(var i=1; i<4; i++) {
    var crazy = prompt("would you marry me?");
         if(crazy === "Yes"|| "yes") {
           console.log("hell ya!");
       }
     /* when it asks "will you marry me" and if the user says either "No" or      "no", it does't print "ok..I'' try again next time". instead, it still says "hell ya !" */
     else if (crazy ==="No" ||"no") {
       console.log("ok..I'll try again next time !");
   }
}
var love = false;
do {
      console.log("nonetheless, I LOVE YOU !");
}
while(love);

【问题讨论】:

  • 条件的语法不正确。您需要再次检查变量。 crazy === 'Yes' || crazy === 'yes'
  • 应该是crazy === "Yes" || crazy === "yes"。 ||'yes' 没有被比较,而是被评估为true。
  • 嘿,非常感谢大家!
  • 很高兴能提供帮助。

标签: javascript for-loop while-loop do-while


【解决方案1】:

试试这样的,

 if(crazy.toUpperCase() === "YES") {
    console.log("hell ya!");
 }

【讨论】:

    【解决方案2】:

    试试这个.. 一段不错的代码.. 它是向某个极客求婚吗?

    i = 0;
        for(var i=1; i<4; i++) {
        var crazy = prompt("would you marry me?");
             if(crazy === "Yes"|| crazy ==="yes") {
               console.log("hell ya!");
           }
         /* when it asks "will you marry me" and if the user says either "No" or      "no", it does't print "ok..I'' try again next time". instead, it still says "hell ya !" */
         else if (crazy ==="No" ||crazy === "no") {
           console.log("ok..I'll try again next time !");
       }
    }
    var love = false;
    do {
          console.log("nonetheless, I LOVE YOU !");
    }
    while(love);
    

    【讨论】:

    • 嘿,非常感谢!这很有帮助..哈哈:)) 不,我没有男朋友,但我想也许有一天这可以帮助一些人减轻压力,让他们的女朋友进入他们的网站,然后真的很有趣,然后哇!
    【解决方案3】:

    解释如下:

    crazy === "Yes" || "yes"
    

    这个语句做了以下事情:

    1. 比较crazy是否与字符串"Yes"相同
    2. 如果它们不相同,“使用”"yes"

    将其放入if 语句中,您将得到:

    • 执行if 块中的所有内容,
      1. …如果crazy 与"Yes" 相同,或
      2. …如果 "yes".

    "yes" 本身在if 语句中的含义是什么?它被评估为 true。

    每个不是空字符串的字符串都被评估为true,每个空字符串都被评估为false。请参阅 Boolean 和 falsy values 上的 MDN 文章。

    您可以通过在控制台中输入像这样的双重否定表达式来验证这一点:

    !!"yes"; // true
    !!"test"; // true
    !!""; // false
    

    你需要做的是第二次比较:

    if(crazy === "Yes" || crazy === "yes")
    

    和

    else if(crazy === "No" || crazy === "no")
    

    替代方法包括 crazy.toLowerCase() === "yes" 仅用于一次比较,或 ["Yes", "yes"].includes(crazy)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多