2014-11-22 60 views
0

该程序似乎工作正常,直到我有两个字符串输入。返回的结果是“未定义”。为什么会这样?我怎样才能得到输出为:return“无法比较关系,因为”+ x +“和”+ y +“不是数字”?当使用Javascript评估两个字符串变量时,“undefined”

function getRelationship(x, y) { 
     var notDigit = isNaN(x) + isNaN(y); 
     if(x==y && notDigit==false){ 
      return "="; 
     }else if(x>y && notDigit==false){ 
      return ">"; 
     }else if(x<y && notDigit==false){ 
      return "<"; 
     }else if(notDigit==true){ 
      return notNumber(x,y); 
     }; 
    }; 
    function notNumber(x, y) { 
     xNotDigit = isNaN(x); 
     yNotDigit = isNaN(y); 
     if(xNotDigit == true){ 
      return "Can\'t compare relationship because "+ x +" is not a number" 
     }else if(yNotDigit == true){ 
      return "Can\'t compare relationship because "+ y +" is not a number" 
     }else if(xNotDigit == true && yNotDigit == true){ 
      return "Can\'t compare relationship because "+ x +" and "+ y +" are not numbers" 
     }; 
    }; 

    console.log(getRelationship("Dfad","Dfd")); 
+0

嗯,这是什么? isNaN(x)+ isNaN(y)'?顺便说一句,不要做'==真'。这是多余的。 – 2014-11-22 03:11:24

+0

当x和y都是数字时,用于这种情况。我不能那样做? – KishB87 2014-11-22 03:14:53

+0

'isNaN'返回一个布尔值,并且你正在向另一个布尔值添加一个布尔值,这是没有意义的。 – 2014-11-22 03:15:49

回答

1

问题出在isNaN('Test') + isNaN('Test')等于2的事实不成立。这是因为当您尝试将true转换为数字时,通过将其添加到另一个数字中,它将转换为1.因此isNaN('Test') + isNaN('Test')将被执行为1 + 1。尝试改变notDigit

var notDigit = isNaN(x) || isNaN(y);