比较两个值时出现JavaScript输出和控制流错误

JavaScript Output and Control Flow errors when comparing two values

本文关键字:JavaScript 输出 错误 控制流 两个 比较      更新时间:2023-09-26

我正试图创建一个程序,比较两个不同的值(x,y),并确定第一个值是否大于、等于或小于另一个值。除此之外,它还将检测输入的值是否为NaN,并输出错误语句。代码如下。。。。

function getRelationship(x, y) {
    if (x > y) {
        return ">";
    }
    else if (x < y) {
        return "<";
    }
    else if (x == y) {
        return "=";
    }
    else if (isNaN(x)) {
        console.log("Can''t compare relationships because " + x + " is not a number");
        return x;
    }
    else if (isNaN(y)) {
        console.log("Can''t compare relationships because " + y + " is not a number");
        return y;
    }
    else if (isNaN(x) && isNaN(y)) {
        console.log("Can''t compare relationships because " + x + " and " + y + " are not numbers");
        return x, y;
    }
}

当我输入以下函数调用时:

console.log(getRelationship(1,4));
console.log(getRelationship(1,1));
console.log(getRelationship("that",2));
console.log(getRelationship("this"," something else")); 
console.log(getRelationship(3)); 
console.log(getRelationship("hi"));
console.log(getRelationship(NaN));
console.log(getRelationship(NaN, undefined));

我把这个拿回来:

LOG: '<'
LOG: '='
LOG: 'Can't compare relationships because that is not a number'
LOG: 'that'
LOG: '>'
LOG: 'Can't compare relationships because undefined is not a number'
LOG: undefined
LOG: 'Can't compare relationships because hi is not a number'
LOG: 'hi'
LOG: 'Can't compare relationships because NaN is not a number'
LOG: NaN
LOG: 'Can't compare relationships because NaN is not a number'
LOG: NaN

所以我的问题是,为什么Else If语句中的第四个函数调用中没有使用&&运算符;"this"answers"something other"是如何被比较的,以及我如何改变它以利用&&条件;当我想要的只是预编码的console.log()输出时,为什么我会得到NaN和其他一些字符串输出?

如何在ElseIf语句中的第四个函数调用中使用&amp;操作员没有被利用?

因为if (isNaN(x))的案子在它之前就已经审理过了,而且确实匹配。

为什么"这个"answers"其他东西"被拿来比较?

好吧,它们都是字符串,为什么不将它们进行比较呢?

我该如何更改

我认为你只想比较数字。在这种情况下,要明确这一点。您可以简单地将两个操作数强制转换为数字(使用Number),但请注意,这也适用于数字字符串。如果您不希望这样,请对操作数进行typeof检查。

当我只想要预先编码的console.log()输出时,为什么我会输出NaN和其他一些字符串?

因为你return给他们打了电话,而且是console.log给你打电话的结果打电话。