"未定义"在Javascript中评估两个字符串变量时

时间:2014-11-22 03:09:30

标签: javascript

这个程序似乎工作正常,直到我有两个字符串输入。返回的结果是“未定义”。为什么会这样?我怎么能得到输出:返回“不能比较关系,因为”+ x +“和”+ y +“不是数字”?

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

1 个答案:

答案 0 :(得分:1)

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

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