在我有两个字符串输入之前,该程序似乎运行良好。返回的结果是“未定义”。为什么会这样呢?我怎么能得到这样的输出:返回“因为“ + 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"));

最佳答案

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

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

关于javascript - 在Javascript中评估两个字符串变量时“未定义”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27073610/

10-13 00:35