或者条件永远不会评估为真

时间:2015-04-23 01:15:48

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

这个javascript代码运行成功,但我认为它没有通过它的"其他"声明,因为它没有打印它的控制台......为什么?

 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);

3 个答案:

答案 0 :(得分:1)

尝试这样的事情,

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

答案 1 :(得分:0)

尝试这个..虽然是一段代码。这对一些讨厌的家伙来说是一个求婚吗?

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);

答案 2 :(得分:0)

以下是解释:

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

此声明执行以下操作:

  1. 比较crazy是否与字符串"Yes"
  2. 相同
  3. 如果它们不相同,请“使用”"yes"
  4. 将其放入if语句中即可得到:

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

    "yes" 本身在if声明中意味着什么?它被评估为 true

    不是空字符串的每个字符串都被评估为true,每个空字符串都被评估为false。请参阅Booleanfalsy 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)