2015-04-23 153 views
0

此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); 
+0

条件的语法不正确。你需要再次检查变量。 '疯狂==='是'||疯狂==='yes'' –

+0

它应该是'疯狂===“是”||疯狂===“是”。'||'yes''不是_compared_,而是评估为'true'。 – Xufox

+0

嘿,非常感谢这么多家伙! –

回答

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

嘿非常感谢你!这是很多的帮助..哈哈:))不,我没有男朋友,但我想也许这可以帮助一些家伙减少压力和实际上有趣的只是告诉他们的女朋友进入他们的网站,然后哇! –

1

尝试这样的事情,

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

非常感谢你。我很感激! –

0

这里的解释:

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

本声明以下的事情:

  1. 它copares crazy是否具有价值是“,如果两者都有(在这种情况下string)同类型
  2. 如果两个类型不匹配或值不匹配,使用“是”

将这个成if语句,你会得到这样的:

  • if块,如果执行一切......
    1. crazyYes的值,如果两者都具有相同类型 ...
    2. ...如果“是”

是什么“是”本身意味着在if声明?它被评估为true

不是空字符串的每个字符串的评估结果为true,每个空字符串评估为false。请参阅MDN source

您可以通过键入像

!!'yes'; // true 
!!'test'; // true 
!!''; // false 

双重否定语句到控制台验证这一点。

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

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

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

另一种方法是crazy.toLowerCase() === "yes"只有一个比较。

+0

非常有价值的信息!非常感谢! –