2014-11-22 98 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);